repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/ide.go | types/enum/ide.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"encoding/json"
"fmt"
)
type IDEType string
func (i IDEType) Enum() []any {
return toInterfaceSlice(ideTypes)
}
func (i *IDEType) String() string {
if i == nil {
return ""
}
return string(*i)
}
var ideTypes = []IDEType{IDETypeVSCode, IDETypeVSCodeWeb, IDETypeCursor, IDETypeWindsurf,
IDETypeIntelliJ, IDETypePyCharm, IDETypeGoland, IDETypeWebStorm, IDETypeCLion, IDETypePHPStorm,
IDETypeRubyMine, IDETypeRider}
var jetBrainsIDESet = map[IDEType]struct{}{
IDETypeIntelliJ: {},
IDETypePyCharm: {},
IDETypeGoland: {},
IDETypeWebStorm: {},
IDETypeCLion: {},
IDETypePHPStorm: {},
IDETypeRubyMine: {},
IDETypeRider: {},
}
const (
IDETypeVSCode IDEType = "vs_code"
IDETypeVSCodeWeb IDEType = "vs_code_web"
// AI-based IDEs.
IDETypeCursor IDEType = "cursor"
IDETypeWindsurf IDEType = "windsurf"
// all jetbrains IDEs.
IDETypeIntelliJ IDEType = "intellij"
IDETypePyCharm IDEType = "pycharm"
IDETypeGoland IDEType = "goland"
IDETypeWebStorm IDEType = "webstorm"
IDETypeCLion IDEType = "clion"
IDETypePHPStorm IDEType = "phpstorm"
IDETypeRubyMine IDEType = "rubymine"
IDETypeRider IDEType = "rider"
)
func IsJetBrainsIDE(t IDEType) bool {
_, exist := jetBrainsIDESet[t]
return exist
}
func (i *IDEType) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
// Accept empty IDE type without failing JSON decode
if s == "" {
*i = ""
return nil
}
for _, v := range ideTypes {
if IDEType(s) == v {
*i = v
return nil
}
}
return fmt.Errorf("invalid IDEType: %s", s)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/ai_agent_auth.go | types/enum/ai_agent_auth.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"encoding/json"
"fmt"
)
type AIAgentAuth string
func (a AIAgentAuth) Enum() []any {
return toInterfaceSlice(AIAgentAuthTypes)
}
func (a AIAgentAuth) String() string {
return string(a)
}
var AIAgentAuthTypes = []AIAgentAuth{
AnthropicAPIKeyAuth,
}
const (
//nolint:gosec // this is not hardcoded credentials
AnthropicAPIKeyAuth AIAgentAuth = "anthropic-api-key"
)
func (a *AIAgentAuth) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
if str == "" {
*a = ""
return nil
}
for _, validType := range AIAgentAuthTypes {
if AIAgentAuth(str) == validType {
*a = validType
return nil
}
}
return fmt.Errorf("invalid AI agent auth type: %s", str)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/webhook.go | types/enum/webhook.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "strings"
// WebhookAttr defines webhook attributes that can be used for sorting and filtering.
type WebhookAttr int
const (
WebhookAttrNone WebhookAttr = iota
// TODO [CODE-1364]: Remove once UID/Identifier migration is completed.
WebhookAttrID
// TODO [CODE-1363]: remove after identifier migration.
WebhookAttrUID
WebhookAttrIdentifier
// TODO [CODE-1364]: Remove once UID/Identifier migration is completed.
WebhookAttrDisplayName
WebhookAttrCreated
WebhookAttrUpdated
)
// ParseWebhookAttr parses the webhook attribute string
// and returns the equivalent enumeration.
func ParseWebhookAttr(s string) WebhookAttr {
switch strings.ToLower(s) {
// TODO [CODE-1364]: Remove once UID/Identifier migration is completed.
case id:
return WebhookAttrID
// TODO [CODE-1363]: remove after identifier migration.
case uid:
return WebhookAttrUID
case identifier:
return WebhookAttrIdentifier
// TODO [CODE-1364]: Remove once UID/Identifier migration is completed.
case displayName:
return WebhookAttrDisplayName
case created, createdAt:
return WebhookAttrCreated
case updated, updatedAt:
return WebhookAttrUpdated
default:
return WebhookAttrNone
}
}
// String returns the string representation of the attribute.
func (a WebhookAttr) String() string {
switch a {
// TODO [CODE-1364]: Remove once UID/Identifier migration is completed.
case WebhookAttrID:
return id
// TODO [CODE-1363]: remove after identifier migration.
case WebhookAttrUID:
return uid
case WebhookAttrIdentifier:
return identifier
// TODO [CODE-1364]: Remove once UID/Identifier migration is completed.
case WebhookAttrDisplayName:
return displayName
case WebhookAttrCreated:
return created
case WebhookAttrUpdated:
return updated
case WebhookAttrNone:
return ""
default:
return undefined
}
}
// WebhookParent defines different types of parents of a webhook.
type WebhookParent string
func (WebhookParent) Enum() []any { return toInterfaceSlice(webhookParents) }
const (
// WebhookParentRepo describes a repo as webhook owner.
WebhookParentRepo WebhookParent = "repo"
// WebhookParentSpace describes a space as webhook owner.
WebhookParentSpace WebhookParent = "space"
// WebhookParentRegistry describes a registry as webhook owner.
WebhookParentRegistry WebhookParent = "registry"
)
var webhookParents = sortEnum([]WebhookParent{
WebhookParentRepo,
WebhookParentSpace,
WebhookParentRegistry,
})
// WebhookExecutionResult defines the different results of a webhook execution.
type WebhookExecutionResult string
func (WebhookExecutionResult) Enum() []any { return toInterfaceSlice(webhookExecutionResults) }
const (
// WebhookExecutionResultSuccess describes a webhook execution result that succeeded.
WebhookExecutionResultSuccess WebhookExecutionResult = "success"
// WebhookExecutionResultRetriableError describes a webhook execution result that failed with a retriable error.
WebhookExecutionResultRetriableError WebhookExecutionResult = "retriable_error"
// WebhookExecutionResultFatalError describes a webhook execution result that failed with an unrecoverable error.
WebhookExecutionResultFatalError WebhookExecutionResult = "fatal_error"
)
var webhookExecutionResults = sortEnum([]WebhookExecutionResult{
WebhookExecutionResultSuccess,
WebhookExecutionResultRetriableError,
WebhookExecutionResultFatalError,
})
// WebhookType defines different types of a webhook.
type WebhookType int
func (WebhookType) Enum() []any { return toInterfaceSlice(webhookTypes) }
const (
// WebhookTypeExternal describes a webhook url pointing to external source.
WebhookTypeExternal WebhookType = iota
// WebhookTypeInternal describes a repo webhook url pointing to internal url.
WebhookTypeInternal
// WebhookTypeJira describes a webhook url pointing to jira.
WebhookTypeJira
)
var webhookTypes = sortEnum([]WebhookType{
WebhookTypeExternal,
WebhookTypeInternal,
WebhookTypeJira,
})
// WebhookTrigger defines the different types of webhook triggers available.
type WebhookTrigger string
func (WebhookTrigger) Enum() []any { return toInterfaceSlice(webhookTriggers) }
func (s WebhookTrigger) Sanitize() (WebhookTrigger, bool) { return Sanitize(s, GetAllWebhookTriggers) }
func GetAllWebhookTriggers() ([]WebhookTrigger, WebhookTrigger) {
return webhookTriggers, "" // No default value
}
const (
// WebhookTriggerBranchCreated gets triggered when a branch gets created.
WebhookTriggerBranchCreated WebhookTrigger = "branch_created"
// WebhookTriggerBranchUpdated gets triggered when a branch gets updated.
WebhookTriggerBranchUpdated WebhookTrigger = "branch_updated"
// WebhookTriggerBranchDeleted gets triggered when a branch gets deleted.
WebhookTriggerBranchDeleted WebhookTrigger = "branch_deleted"
// WebhookTriggerTagCreated gets triggered when a tag gets created.
WebhookTriggerTagCreated WebhookTrigger = "tag_created"
// WebhookTriggerTagUpdated gets triggered when a tag gets updated.
WebhookTriggerTagUpdated WebhookTrigger = "tag_updated"
// WebhookTriggerTagDeleted gets triggered when a tag gets deleted.
WebhookTriggerTagDeleted WebhookTrigger = "tag_deleted"
// WebhookTriggerPullReqCreated gets triggered when a pull request gets created.
WebhookTriggerPullReqCreated WebhookTrigger = "pullreq_created"
// WebhookTriggerPullReqReopened gets triggered when a pull request gets reopened.
WebhookTriggerPullReqReopened WebhookTrigger = "pullreq_reopened"
// WebhookTriggerPullReqBranchUpdated gets triggered when a pull request source branch gets updated.
WebhookTriggerPullReqBranchUpdated WebhookTrigger = "pullreq_branch_updated"
// WebhookTriggerPullReqClosed gets triggered when a pull request is closed.
WebhookTriggerPullReqClosed WebhookTrigger = "pullreq_closed"
// WebhookTriggerPullReqCommentCreated gets triggered when a pull request comment gets created.
WebhookTriggerPullReqCommentCreated WebhookTrigger = "pullreq_comment_created"
// WebhookTriggerPullReqCommentUpdated gets triggered when a pull request comment gets edited.
WebhookTriggerPullReqCommentUpdated WebhookTrigger = "pullreq_comment_updated"
// WebhookTriggerPullReqCommentStatusUpdated gets triggered when a pull request comment status gets updated.
WebhookTriggerPullReqCommentStatusUpdated WebhookTrigger = "pullreq_comment_status_updated"
// WebhookTriggerPullReqMerged gets triggered when a pull request is merged.
WebhookTriggerPullReqMerged WebhookTrigger = "pullreq_merged"
// WebhookTriggerPullReqUpdated gets triggered when a pull request gets updated.
WebhookTriggerPullReqUpdated WebhookTrigger = "pullreq_updated"
// WebhookTriggerPullReqLabelAssigned gets triggered when a label is assigned to a pull request.
WebhookTriggerPullReqLabelAssigned WebhookTrigger = "pullreq_label_assigned"
// WebhookTriggerPullReqReviewSubmitted gets triggered when a pull request review is submitted.
WebhookTriggerPullReqReviewSubmitted = "pullreq_review_submitted"
// WebhookTriggerPullReqTargetBranchChanged gets triggered when a pull request target branch is changed.
WebhookTriggerPullReqTargetBranchChanged = "pullreq_target_branch_changed"
// WebhookTriggerArtifactCreated gets triggered when an artifact gets created.
WebhookTriggerArtifactCreated WebhookTrigger = "artifact_created"
// WebhookTriggerArtifactDeleted gets triggered when an artifact gets deleted.
WebhookTriggerArtifactDeleted WebhookTrigger = "artifact_deleted"
)
var webhookTriggers = sortEnum([]WebhookTrigger{
WebhookTriggerBranchCreated,
WebhookTriggerBranchUpdated,
WebhookTriggerBranchDeleted,
WebhookTriggerTagCreated,
WebhookTriggerTagUpdated,
WebhookTriggerTagDeleted,
WebhookTriggerPullReqCreated,
WebhookTriggerPullReqUpdated,
WebhookTriggerPullReqReopened,
WebhookTriggerPullReqBranchUpdated,
WebhookTriggerPullReqClosed,
WebhookTriggerPullReqCommentCreated,
WebhookTriggerPullReqCommentUpdated,
WebhookTriggerPullReqCommentStatusUpdated,
WebhookTriggerPullReqMerged,
WebhookTriggerPullReqLabelAssigned,
WebhookTriggerPullReqReviewSubmitted,
WebhookTriggerPullReqTargetBranchChanged,
WebhookTriggerArtifactCreated,
WebhookTriggerArtifactDeleted,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/sse.go | types/enum/sse.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// SSEType defines the kind of server sent event.
type SSEType string
// Enums for event types delivered to the event stream for the UI.
const (
// Executions.
SSETypeExecutionUpdated SSEType = "execution_updated"
SSETypeExecutionRunning SSEType = "execution_running"
SSETypeExecutionCompleted SSEType = "execution_completed"
SSETypeExecutionCanceled SSEType = "execution_canceled"
// Repo import/export.
SSETypeRepositoryImportCompleted SSEType = "repository_import_completed"
SSETypeRepositoryExportCompleted SSEType = "repository_export_completed"
// Pull reqs.
SSETypePullReqUpdated SSEType = "pullreq_updated"
SSETypePullReqReviewerAdded SSEType = "pullreq_reviewer_added"
SSETypePullReqtReviewerRemoved SSEType = "pullreq_reviewer_removed"
SSETypePullReqCommentCreated SSEType = "pullreq_comment_created"
SSETypePullReqCommentEdited SSEType = "pullreq_comment_edited"
SSETypePullReqCommentUpdated SSEType = "pullreq_comment_updated"
SSETypePullReqCommentStatusResolved SSEType = "pullreq_comment_status_resolved"
SSETypePullReqCommentStatusReactivated SSEType = "pullreq_comment_status_reactivated"
SSETypePullReqOpened SSEType = "pullreq_opened"
SSETypePullReqClosed SSEType = "pullreq_closed"
SSETypePullReqMarkedAsDraft SSEType = "pullreq_marked_as_draft"
SSETypePullReqReadyForReview SSEType = "pullreq_ready_for_review"
// Branches.
SSETypeBranchMergableUpdated SSEType = "branch_mergable_updated"
SSETypeBranchCreated SSEType = "branch_created"
SSETypeBranchUpdated SSEType = "branch_updated"
SSETypeBranchDeleted SSEType = "branch_deleted"
// Tags.
SSETypeTagCreated SSEType = "tag_created"
SSETypeTagUpdated SSEType = "tag_updated"
SSETypeTagDeleted SSEType = "tag_deleted"
// Statuses.
SSETypeStatusCheckReportUpdated SSEType = "status_check_report_updated"
// Logs.
SSETypeLogLineAppended SSEType = "log_line_appended"
// Rules.
SSETypeRuleCreated SSEType = "rule_created"
SSETypeRuleUpdated SSEType = "rule_updated"
SSETypeRuleDeleted SSEType = "rule_deleted"
// Webhooks.
SSETypeWebhookCreated SSEType = "webhook_created"
SSETypeWebhookUpdated SSEType = "webhook_updated"
SSETypeWebhookDeleted SSEType = "webhook_deleted"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/gitspace_operations_event.go | types/enum/gitspace_operations_event.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type GitspaceOperationsEvent string
func (GitspaceOperationsEvent) Enum() []any {
return toInterfaceSlice(gitspaceOperationsEvent)
}
var gitspaceOperationsEvent = []GitspaceOperationsEvent{
GitspaceOperationsEventStart, GitspaceOperationsEventStop, GitspaceOperationsEventDelete,
}
const (
GitspaceOperationsEventStart GitspaceOperationsEvent = "start"
GitspaceOperationsEventStop GitspaceOperationsEvent = "stop"
GitspaceOperationsEventDelete GitspaceOperationsEvent = "delete"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/gitspace_event_type.go | types/enum/gitspace_event_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type GitspaceEventType string
func (GitspaceEventType) Enum() []any {
return toInterfaceSlice(gitspaceEventTypes)
}
var gitspaceEventTypes = []GitspaceEventType{
GitspaceEventTypeGitspaceActionStart,
GitspaceEventTypeGitspaceActionStartCompleted,
GitspaceEventTypeGitspaceActionStartFailed,
GitspaceEventTypeGitspaceActionStop,
GitspaceEventTypeGitspaceActionStopCompleted,
GitspaceEventTypeGitspaceActionStopFailed,
GitspaceEventTypeFetchDevcontainerStart,
GitspaceEventTypeFetchDevcontainerCompleted,
GitspaceEventTypeFetchDevcontainerFailed,
GitspaceEventTypeInfraProvisioningStart,
GitspaceEventTypeInfraProvisioningCompleted,
GitspaceEventTypeInfraProvisioningFailed,
GitspaceEventTypeInfraStopStart,
GitspaceEventTypeInfraStopCompleted,
GitspaceEventTypeInfraStopFailed,
GitspaceEventTypeInfraDeprovisioningStart,
GitspaceEventTypeInfraDeprovisioningCompleted,
GitspaceEventTypeInfraDeprovisioningFailed,
GitspaceEventTypeAgentConnectStart,
GitspaceEventTypeAgentConnectCompleted,
GitspaceEventTypeAgentConnectFailed,
GitspaceEventTypeAgentGitspaceCreationStart,
GitspaceEventTypeAgentGitspaceCreationCompleted,
GitspaceEventTypeAgentGitspaceCreationFailed,
GitspaceEventTypeAgentGitspaceStopStart,
GitspaceEventTypeAgentGitspaceStopCompleted,
GitspaceEventTypeAgentGitspaceStopFailed,
GitspaceEventTypeAgentGitspaceDeletionStart,
GitspaceEventTypeAgentGitspaceDeletionCompleted,
GitspaceEventTypeAgentGitspaceDeletionFailed,
GitspaceEventTypeAgentGitspaceStateReportRunning,
GitspaceEventTypeAgentGitspaceStateReportError,
GitspaceEventTypeAgentGitspaceStateReportStopped,
GitspaceEventTypeAgentGitspaceStateReportUnknown,
GitspaceEventTypeGitspaceAutoStop,
GitspaceEventTypeGitspaceActionReset,
GitspaceEventTypeGitspaceActionResetCompleted,
GitspaceEventTypeGitspaceActionResetFailed,
}
const (
// Start action events.
GitspaceEventTypeGitspaceActionStart GitspaceEventType = "gitspace_action_start"
GitspaceEventTypeGitspaceActionStartCompleted GitspaceEventType = "gitspace_action_start_completed"
GitspaceEventTypeGitspaceActionStartFailed GitspaceEventType = "gitspace_action_start_failed"
// Stop action events.
GitspaceEventTypeGitspaceActionStop GitspaceEventType = "gitspace_action_stop"
GitspaceEventTypeGitspaceActionStopCompleted GitspaceEventType = "gitspace_action_stop_completed"
GitspaceEventTypeGitspaceActionStopFailed GitspaceEventType = "gitspace_action_stop_failed"
// Reset action events.
GitspaceEventTypeGitspaceActionReset = "gitspace_action_reset"
GitspaceEventTypeGitspaceActionResetCompleted GitspaceEventType = "gitspace_action_reset_completed"
GitspaceEventTypeGitspaceActionResetFailed GitspaceEventType = "gitspace_action_reset_failed"
// Fetch devcontainer config events.
GitspaceEventTypeFetchDevcontainerStart GitspaceEventType = "fetch_devcontainer_start"
GitspaceEventTypeFetchDevcontainerCompleted GitspaceEventType = "fetch_devcontainer_completed"
GitspaceEventTypeFetchDevcontainerFailed GitspaceEventType = "fetch_devcontainer_failed"
// Fetch artifact registry secret.
GitspaceEventTypeFetchConnectorsDetailsStart GitspaceEventType = "fetch_connectors_details_start"
GitspaceEventTypeFetchConnectorsDetailsCompleted GitspaceEventType = "fetch_connectors_details_completed" //nolint
GitspaceEventTypeFetchConnectorsDetailsFailed GitspaceEventType = "fetch_connectors_details_failed"
// Infra provisioning events.
GitspaceEventTypeInfraProvisioningStart GitspaceEventType = "infra_provisioning_start"
GitspaceEventTypeInfraProvisioningCompleted GitspaceEventType = "infra_provisioning_completed"
GitspaceEventTypeInfraProvisioningFailed GitspaceEventType = "infra_provisioning_failed"
// Gateway update events.
GitspaceEventTypeInfraGatewayRouteStart GitspaceEventType = "infra_gateway_route_start"
GitspaceEventTypeInfraGatewayRouteCompleted GitspaceEventType = "infra_gateway_route_completed"
GitspaceEventTypeInfraGatewayRouteFailed GitspaceEventType = "infra_gateway_route_failed"
// Infra stop events.
GitspaceEventTypeInfraStopStart GitspaceEventType = "infra_stop_start"
GitspaceEventTypeInfraStopCompleted GitspaceEventType = "infra_stop_completed"
GitspaceEventTypeInfraStopFailed GitspaceEventType = "infra_stop_failed"
// Infra cleanup events.
GitspaceEventTypeInfraCleanupStart GitspaceEventType = "infra_cleanup_start"
GitspaceEventTypeInfraCleanupCompleted GitspaceEventType = "infra_cleanup_completed"
GitspaceEventTypeInfraCleanupFailed GitspaceEventType = "infra_cleanup_failed"
// Infra deprovisioning events.
GitspaceEventTypeInfraDeprovisioningStart GitspaceEventType = "infra_deprovisioning_start"
GitspaceEventTypeInfraDeprovisioningCompleted GitspaceEventType = "infra_deprovisioning_completed"
GitspaceEventTypeInfraDeprovisioningFailed GitspaceEventType = "infra_deprovisioning_failed"
// Agent connection events.
GitspaceEventTypeAgentConnectStart GitspaceEventType = "agent_connect_start"
GitspaceEventTypeAgentConnectCompleted GitspaceEventType = "agent_connect_completed"
GitspaceEventTypeAgentConnectFailed GitspaceEventType = "agent_connect_failed"
// Gitspace creation events.
GitspaceEventTypeAgentGitspaceCreationStart GitspaceEventType = "agent_gitspace_creation_start"
GitspaceEventTypeAgentGitspaceCreationCompleted GitspaceEventType = "agent_gitspace_creation_completed"
GitspaceEventTypeAgentGitspaceCreationFailed GitspaceEventType = "agent_gitspace_creation_failed"
// Gitspace stop events.
GitspaceEventTypeAgentGitspaceStopStart GitspaceEventType = "agent_gitspace_stop_start"
GitspaceEventTypeAgentGitspaceStopCompleted GitspaceEventType = "agent_gitspace_stop_completed"
GitspaceEventTypeAgentGitspaceStopFailed GitspaceEventType = "agent_gitspace_stop_failed"
// Gitspace deletion events.
GitspaceEventTypeAgentGitspaceDeletionStart GitspaceEventType = "agent_gitspace_deletion_start"
GitspaceEventTypeAgentGitspaceDeletionCompleted GitspaceEventType = "agent_gitspace_deletion_completed"
GitspaceEventTypeAgentGitspaceDeletionFailed GitspaceEventType = "agent_gitspace_deletion_failed"
// Gitspace state events.
GitspaceEventTypeAgentGitspaceStateReportRunning GitspaceEventType = "agent_gitspace_state_report_running"
GitspaceEventTypeAgentGitspaceStateReportError GitspaceEventType = "agent_gitspace_state_report_error"
GitspaceEventTypeAgentGitspaceStateReportStopped GitspaceEventType = "agent_gitspace_state_report_stopped"
GitspaceEventTypeAgentGitspaceStateReportUnknown GitspaceEventType = "agent_gitspace_state_report_unknown"
// AutoStop action event.
GitspaceEventTypeGitspaceAutoStop GitspaceEventType = "gitspace_action_auto_stop"
// Cleanup job events.
GitspaceEventTypeGitspaceCleanupJob GitspaceEventType = "gitspace_action_cleanup_job"
// Infra reset events.
GitspaceEventTypeInfraResetStart GitspaceEventType = "infra_reset_start"
GitspaceEventTypeInfraResetFailed GitspaceEventType = "infra_reset_failed"
GitspaceEventTypeDelegateTaskSubmitted GitspaceEventType = "delegate_task_submitted"
GitspaceEventTypeInfraVMCreationStart GitspaceEventType = "infra_vm_creation_start"
GitspaceEventTypeInfraVMCreationCompleted GitspaceEventType = "infra_vm_creation_completed"
GitspaceEventTypeInfraVMCreationFailed GitspaceEventType = "infra_vm_creation_failed"
GitspaceEventTypeInfraPublishGatewayCompleted GitspaceEventType = "infra_publish_gateway_completed"
GitspaceEventTypeInfraPublishGatewayFailed GitspaceEventType = "infra_publish_gateway_failed"
)
func EventsMessageMapping() map[GitspaceEventType]string {
var gitspaceConfigsMap = map[GitspaceEventType]string{
GitspaceEventTypeGitspaceActionStart: "Setting up Gitspace...",
GitspaceEventTypeGitspaceActionStartCompleted: "Gitspace set up successfully",
GitspaceEventTypeGitspaceActionStartFailed: "Failed to set up Gitspace",
GitspaceEventTypeGitspaceActionStop: "Stopping Gitspace...",
GitspaceEventTypeGitspaceActionStopCompleted: "Gitspace stopped successfully",
GitspaceEventTypeGitspaceActionStopFailed: "Failed to stop Gitspace",
GitspaceEventTypeGitspaceActionReset: "Resetting Gitspace...",
GitspaceEventTypeGitspaceActionResetCompleted: "Gitspace reset successfully",
GitspaceEventTypeGitspaceActionResetFailed: "Failed to reset Gitspace",
GitspaceEventTypeFetchDevcontainerStart: "Fetching Devcontainer configuration...",
GitspaceEventTypeFetchDevcontainerCompleted: "Devcontainer configuration fetched",
GitspaceEventTypeFetchDevcontainerFailed: "Failed to fetch Devcontainer configuration",
GitspaceEventTypeFetchConnectorsDetailsStart: "Fetching platform connector details...",
GitspaceEventTypeFetchConnectorsDetailsCompleted: "Platform connector details fetched",
GitspaceEventTypeFetchConnectorsDetailsFailed: "Failed to fetch platform connector details",
GitspaceEventTypeInfraProvisioningStart: "Provisioning infrastructure...",
GitspaceEventTypeInfraProvisioningCompleted: "Infrastructure provisioned successfully",
GitspaceEventTypeInfraProvisioningFailed: "Failed to provision infrastructure",
GitspaceEventTypeInfraGatewayRouteStart: "Updating gateway routing...",
GitspaceEventTypeInfraGatewayRouteCompleted: "Gateway routing updated successfully",
GitspaceEventTypeInfraGatewayRouteFailed: "Failed to update gateway routing",
GitspaceEventTypeInfraStopStart: "Stopping infrastructure...",
GitspaceEventTypeInfraStopCompleted: "Infrastructure stopped successfully",
GitspaceEventTypeInfraStopFailed: "Failed to stop infrastructure",
GitspaceEventTypeInfraDeprovisioningStart: "Deprovisioning infrastructure...",
GitspaceEventTypeInfraDeprovisioningCompleted: "Infrastructure deprovisioned successfully",
GitspaceEventTypeInfraDeprovisioningFailed: "Failed to deprovision infrastructure",
GitspaceEventTypeAgentConnectStart: "Connecting to Gitspace agent...",
GitspaceEventTypeAgentConnectCompleted: "Connected to Gitspace agent",
GitspaceEventTypeAgentConnectFailed: "Failed to connect to Gitspace agent",
GitspaceEventTypeAgentGitspaceCreationStart: "Setting up Gitspace container...",
GitspaceEventTypeAgentGitspaceCreationCompleted: "Gitspace container set up successfully",
GitspaceEventTypeAgentGitspaceCreationFailed: "Failed to set up Gitspace",
GitspaceEventTypeAgentGitspaceStopStart: "Stopping Gitspace container...",
GitspaceEventTypeAgentGitspaceStopCompleted: "Gitspace container stopped successfully",
GitspaceEventTypeAgentGitspaceStopFailed: "Failed to stop Gitspace contaier",
GitspaceEventTypeAgentGitspaceDeletionStart: "Removing Gitspace...",
GitspaceEventTypeAgentGitspaceDeletionCompleted: "Gitspace removed successfully",
GitspaceEventTypeAgentGitspaceDeletionFailed: "Failed to remove Gitspace",
GitspaceEventTypeAgentGitspaceStateReportRunning: "Gitspace is running",
GitspaceEventTypeAgentGitspaceStateReportStopped: "Gitspace is stopped",
GitspaceEventTypeAgentGitspaceStateReportUnknown: "Gitspace state is unknown",
GitspaceEventTypeAgentGitspaceStateReportError: "Gitspace encountered an error",
GitspaceEventTypeGitspaceAutoStop: "Auto-stopping Gitspace due to inactivity...",
GitspaceEventTypeGitspaceCleanupJob: "Running Gitspace cleanup job...",
GitspaceEventTypeInfraCleanupStart: "Cleaning up infrastructure...",
GitspaceEventTypeInfraCleanupCompleted: "Infrastructure cleaned up successfully",
GitspaceEventTypeInfraCleanupFailed: "Failed to clean up infrastructure",
GitspaceEventTypeInfraResetStart: "Resetting infrastructure for Gitspace...",
GitspaceEventTypeInfraResetFailed: "Failed to reset infrastructure for Gitspace",
GitspaceEventTypeDelegateTaskSubmitted: "Delegate task submitted",
GitspaceEventTypeInfraVMCreationStart: "Creating virtual machine...",
GitspaceEventTypeInfraVMCreationCompleted: "Virtual machine created successfully",
GitspaceEventTypeInfraVMCreationFailed: "Failed to create virtual machine",
GitspaceEventTypeInfraPublishGatewayCompleted: "Published machine port mapping to gateway",
GitspaceEventTypeInfraPublishGatewayFailed: "Failed to publish machine port mapping to gateway",
}
return gitspaceConfigsMap
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/resolver_type.go | types/enum/resolver_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "fmt"
// ResolverType represents the type of resolver.
type ResolverType string
const (
// ResolverTypeStep is a step level resolver.
ResolverTypeStep ResolverType = "step"
// ResolverTypeStage is a stage level resolver.
ResolverTypeStage ResolverType = "stage"
)
func ParseResolverType(s string) (ResolverType, error) {
switch s {
case "step":
return ResolverTypeStep, nil
case "stage":
return ResolverTypeStage, nil
default:
return "", fmt.Errorf("unknown template type provided: %s", s)
}
}
func (t ResolverType) String() string {
switch t {
case ResolverTypeStep:
return "step"
case ResolverTypeStage:
return "stage"
default:
return undefined
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/trigger_events.go | types/enum/trigger_events.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// TriggerEvent defines the different kinds of events in triggers.
type TriggerEvent string
// Hook event constants.
const (
TriggerEventCron TriggerEvent = "cron"
TriggerEventManual TriggerEvent = "manual"
TriggerEventPush TriggerEvent = "push"
TriggerEventPullRequest TriggerEvent = "pull_request"
TriggerEventTag TriggerEvent = "tag"
)
// Enum returns all possible TriggerEvent values.
func (TriggerEvent) Enum() []any {
return toInterfaceSlice(triggerEvents)
}
// Sanitize validates and returns a sanitized TriggerEvent value.
func (event TriggerEvent) Sanitize() (TriggerEvent, bool) {
return Sanitize(event, GetAllTriggerEvents)
}
// GetAllTriggerEvents returns all possible TriggerEvent values and a default value.
func GetAllTriggerEvents() ([]TriggerEvent, TriggerEvent) {
return triggerEvents, TriggerEventManual
}
// List of all TriggerEvent values.
var triggerEvents = sortEnum([]TriggerEvent{
TriggerEventCron,
TriggerEventManual,
TriggerEventPush,
TriggerEventPullRequest,
TriggerEventTag,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/membership.go | types/enum/membership.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"strings"
)
// MembershipUserSort represents membership user sort order.
type MembershipUserSort string
// MembershipUserSort enumeration.
const (
MembershipUserSortName MembershipUserSort = name
MembershipUserSortCreated MembershipUserSort = created
)
var membershipUserSorts = sortEnum([]MembershipUserSort{
MembershipUserSortName,
MembershipUserSortCreated,
})
func (MembershipUserSort) Enum() []any { return toInterfaceSlice(membershipUserSorts) }
func (s MembershipUserSort) Sanitize() (MembershipUserSort, bool) {
return Sanitize(s, GetAllMembershipUserSorts)
}
func GetAllMembershipUserSorts() ([]MembershipUserSort, MembershipUserSort) {
return membershipUserSorts, MembershipUserSortName
}
// ParseMembershipUserSort parses the membership user sort attribute string
// and returns the equivalent enumeration.
func ParseMembershipUserSort(s string) MembershipUserSort {
switch strings.ToLower(s) {
case name:
return MembershipUserSortName
case created, createdAt:
return MembershipUserSortCreated
default:
return MembershipUserSortName
}
}
// String returns the string representation of the attribute.
func (s MembershipUserSort) String() string {
switch s {
case MembershipUserSortName:
return name
case MembershipUserSortCreated:
return created
default:
return undefined
}
}
// MembershipSpaceSort represents membership space sort order.
type MembershipSpaceSort string
// MembershipSpaceSort enumeration.
const (
// TODO [CODE-1363]: remove after identifier migration.
MembershipSpaceSortUID MembershipSpaceSort = uid
MembershipSpaceSortIdentifier MembershipSpaceSort = identifier
MembershipSpaceSortCreated MembershipSpaceSort = created
)
var membershipSpaceSorts = sortEnum([]MembershipSpaceSort{
// TODO [CODE-1363]: remove after identifier migration.
MembershipSpaceSortUID,
MembershipSpaceSortIdentifier,
MembershipSpaceSortCreated,
})
func (MembershipSpaceSort) Enum() []any { return toInterfaceSlice(membershipSpaceSorts) }
func (s MembershipSpaceSort) Sanitize() (MembershipSpaceSort, bool) {
return Sanitize(s, GetAllMembershipSpaceSorts)
}
func GetAllMembershipSpaceSorts() ([]MembershipSpaceSort, MembershipSpaceSort) {
// TODO [CODE-1363]: remove after identifier migration.
return membershipSpaceSorts, MembershipSpaceSortIdentifier
}
// ParseMembershipSpaceSort parses the membership space sort attribute string
// and returns the equivalent enumeration.
func ParseMembershipSpaceSort(s string) MembershipSpaceSort {
switch strings.ToLower(s) {
case name, identifier:
return MembershipSpaceSortIdentifier
// TODO [CODE-1363]: remove after identifier migration.
case uid:
return MembershipSpaceSortUID
case created, createdAt:
return MembershipSpaceSortCreated
default:
return MembershipSpaceSortIdentifier
}
}
// String returns the string representation of the attribute.
func (s MembershipSpaceSort) String() string {
switch s {
// TODO [CODE-1363]: remove after identifier migration.
case MembershipSpaceSortUID:
return uid
case MembershipSpaceSortIdentifier:
return identifier
case MembershipSpaceSortCreated:
return created
default:
return undefined
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/git_lfs.go | types/enum/git_lfs.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"fmt"
"strings"
)
type GitLFSTransferType string
const (
GitLFSTransferTypeBasic GitLFSTransferType = "basic"
GitLFSTransferTypeSSH GitLFSTransferType = "ssh"
// TODO GitLFSTransferTypeMultipart
)
func ParseGitLFSTransferType(s string) (GitLFSTransferType, error) {
switch strings.ToLower(s) {
case string(GitLFSTransferTypeBasic):
return GitLFSTransferTypeBasic, nil
case string(GitLFSTransferTypeSSH):
return GitLFSTransferTypeSSH, nil
default:
return "", fmt.Errorf("unknown git-lfs transfer type provided: %q", s)
}
}
type GitLFSOperationType string
const (
GitLFSOperationTypeDownload GitLFSOperationType = "download"
GitLFSOperationTypeUpload GitLFSOperationType = "upload"
)
func ParseGitLFSOperationType(s string) (GitLFSOperationType, error) {
switch strings.ToLower(s) {
case string(GitLFSOperationTypeDownload):
return GitLFSOperationTypeDownload, nil
case string(GitLFSOperationTypeUpload):
return GitLFSOperationTypeUpload, nil
default:
return "", fmt.Errorf("unknown git-lfs operation type provided: %q", s)
}
}
// GitLFSServiceType represents the different types of services git-lfs client sends over ssh.
type GitLFSServiceType string
const (
// GitLFSServiceTypeTransfer is sent by git lfs client for transfer LFS objects.
GitLFSServiceTypeTransfer GitLFSServiceType = "git-lfs-transfer"
// GitLFSServiceTypeAuthenticate is sent by git lfs client for authentication.
GitLFSServiceTypeAuthenticate GitLFSServiceType = "git-lfs-authenticate"
)
func ParseGitLFSServiceType(s string) (GitLFSServiceType, error) {
switch strings.ToLower(s) {
case string(GitLFSServiceTypeTransfer):
return GitLFSServiceTypeTransfer, nil
case string(GitLFSServiceTypeAuthenticate):
return GitLFSServiceTypeAuthenticate, nil
default:
return "", fmt.Errorf("unknown git-lfs service type provided: %q", s)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/token.go | types/enum/token.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// TokenType represents the type of the JWT token.
type TokenType string
const (
// TokenTypeSession is the token returned during user login or signup.
TokenTypeSession TokenType = "session"
// TokenTypePAT is a personal access token.
TokenTypePAT TokenType = "pat"
// TokenTypeSAT is a service account access token.
TokenTypeSAT TokenType = "sat"
// TokenTypeRemoteAuth is the token returned during ssh git-lfs-authenticate.
TokenTypeRemoteAuth TokenType = "remoteAuth"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/ai_task_event.go | types/enum/ai_task_event.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type AITaskEvent string
func (AITaskEvent) Enum() []any {
return toInterfaceSlice(aiTaskEvent)
}
var aiTaskEvent = []AITaskEvent{
AITaskEventStart, AITaskEventStop,
}
const (
AITaskEventStart AITaskEvent = "start"
AITaskEventStop AITaskEvent = "stop"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/connector_auth_type.go | types/enum/connector_auth_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "fmt"
// ConnectorAuthType represents the type of connector authentication.
type ConnectorAuthType string
const (
ConnectorAuthTypeBasic ConnectorAuthType = "basic"
ConnectorAuthTypeBearer ConnectorAuthType = "bearer"
)
func ParseConnectorAuthType(s string) (ConnectorAuthType, error) {
switch s {
case "basic":
return ConnectorAuthTypeBasic, nil
case "bearer":
return ConnectorAuthTypeBearer, nil
default:
return "", fmt.Errorf("unknown connector auth type provided: %s", s)
}
}
func (t ConnectorAuthType) String() string {
switch t {
case ConnectorAuthTypeBasic:
return "basic"
case ConnectorAuthTypeBearer:
return "bearer"
default:
return "undefined"
}
}
func GetAllConnectorAuthTypes() []ConnectorAuthType {
return []ConnectorAuthType{
ConnectorAuthTypeBasic,
ConnectorAuthTypeBearer,
}
}
func (ConnectorAuthType) Enum() []any { return toInterfaceSlice(GetAllConnectorAuthTypes()) }
func (t ConnectorAuthType) Sanitize() (ConnectorAuthType, bool) {
return Sanitize(t, func() ([]ConnectorAuthType, ConnectorAuthType) {
return GetAllConnectorAuthTypes(), ""
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/provisioning_type.go | types/enum/provisioning_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type InfraProvisioningType string
func (InfraProvisioningType) Enum() []any { return toInterfaceSlice(provisioningTypes) }
var provisioningTypes = []InfraProvisioningType{
InfraProvisioningTypeExisting, InfraProvisioningTypeNew,
}
const (
InfraProvisioningTypeExisting InfraProvisioningType = "existing"
InfraProvisioningTypeNew InfraProvisioningType = "new"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/execution.go | types/enum/execution.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// ExecutionSort defines execution attribute that can be used for sorting.
type ExecutionSort string
func (ExecutionSort) Enum() []any { return toInterfaceSlice(executionSorts) }
func (s ExecutionSort) Sanitize() (ExecutionSort, bool) { return Sanitize(s, GetAllExecutionSorts) }
func GetAllExecutionSorts() ([]ExecutionSort, ExecutionSort) {
return executionSorts, ExecutionSortStarted
}
// ExecutionSort enumeration.
const (
ExecutionSortStarted = "started"
ExecutionSortFinished = "finished"
)
var executionSorts = sortEnum([]ExecutionSort{
ExecutionSortStarted,
ExecutionSortFinished,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/check.go | types/enum/check.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "golang.org/x/exp/slices"
// CheckStatus defines status check status.
type CheckStatus string
func (CheckStatus) Enum() []any { return toInterfaceSlice(checkStatuses) }
func (s CheckStatus) Sanitize() (CheckStatus, bool) { return Sanitize(s, GetAllCheckStatuses) }
func GetAllCheckStatuses() ([]CheckStatus, CheckStatus) { return checkStatuses, "" }
// CheckStatus enumeration.
const (
CheckStatusPending CheckStatus = "pending"
CheckStatusRunning CheckStatus = "running"
CheckStatusSuccess CheckStatus = "success"
CheckStatusFailure CheckStatus = "failure"
CheckStatusError CheckStatus = "error"
CheckStatusFailureIgnored CheckStatus = "failure_ignored"
)
var checkStatuses = sortEnum([]CheckStatus{
CheckStatusPending,
CheckStatusRunning,
CheckStatusSuccess,
CheckStatusFailure,
CheckStatusError,
CheckStatusFailureIgnored,
})
var terminalCheckStatuses = []CheckStatus{CheckStatusFailure, CheckStatusSuccess, CheckStatusError,
CheckStatusFailureIgnored}
var successCheckStatuses = []CheckStatus{CheckStatusSuccess, CheckStatusFailureIgnored}
// CheckPayloadKind defines status payload type.
type CheckPayloadKind string
func (CheckPayloadKind) Enum() []any { return toInterfaceSlice(checkPayloadTypes) }
func (s CheckPayloadKind) Sanitize() (CheckPayloadKind, bool) {
return Sanitize(s, GetAllCheckPayloadTypes)
}
func GetAllCheckPayloadTypes() ([]CheckPayloadKind, CheckPayloadKind) {
return checkPayloadTypes, CheckPayloadKindEmpty
}
// CheckPayloadKind enumeration.
const (
CheckPayloadKindEmpty CheckPayloadKind = ""
CheckPayloadKindRaw CheckPayloadKind = "raw"
CheckPayloadKindMarkdown CheckPayloadKind = "markdown"
CheckPayloadKindPipeline CheckPayloadKind = "pipeline"
)
var checkPayloadTypes = sortEnum([]CheckPayloadKind{
CheckPayloadKindEmpty,
CheckPayloadKindRaw,
CheckPayloadKindMarkdown,
CheckPayloadKindPipeline,
})
func (s CheckStatus) IsCompleted() bool {
return slices.Contains(terminalCheckStatuses, s)
}
func (s CheckStatus) IsSuccess() bool {
return slices.Contains(successCheckStatuses, s)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/ci_status.go | types/enum/ci_status.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Status types for CI.
package enum
import (
"strings"
)
// CIStatus defines the different kinds of CI statuses for
// stages, steps and executions.
type CIStatus string
const (
CIStatusSkipped CIStatus = "skipped"
CIStatusBlocked CIStatus = "blocked"
CIStatusDeclined CIStatus = "declined"
CIStatusWaitingOnDeps CIStatus = "waiting_on_dependencies"
CIStatusPending CIStatus = "pending"
CIStatusRunning CIStatus = "running"
CIStatusSuccess CIStatus = "success"
CIStatusFailure CIStatus = "failure"
CIStatusKilled CIStatus = "killed"
CIStatusError CIStatus = "error"
)
// Enum returns all possible CIStatus values.
func (CIStatus) Enum() []any {
return toInterfaceSlice(ciStatuses)
}
// Sanitize validates and returns a sanitized CIStatus value.
func (status CIStatus) Sanitize() (CIStatus, bool) {
return Sanitize(status, GetAllCIStatuses)
}
// GetAllCIStatuses returns all possible CIStatus values and a default value.
func GetAllCIStatuses() ([]CIStatus, CIStatus) {
return ciStatuses, CIStatusPending
}
func (status CIStatus) ConvertToCheckStatus() CheckStatus {
if status == CIStatusPending || status == CIStatusWaitingOnDeps {
return CheckStatusPending
}
if status == CIStatusSuccess || status == CIStatusSkipped {
return CheckStatusSuccess
}
if status == CIStatusFailure {
return CheckStatusFailure
}
if status == CIStatusRunning {
return CheckStatusRunning
}
return CheckStatusError
}
// ParseCIStatus converts the status from a string to typed enum.
// If the match is not exact, will just return default error status
// instead of explicitly returning not found error.
func ParseCIStatus(status string) CIStatus {
switch strings.ToLower(status) {
case "skipped", "blocked", "declined", "waiting_on_dependencies",
"pending", "running", "success", "failure", "killed", "error":
return CIStatus(strings.ToLower(status))
case "": // just in case status is not passed through
return CIStatusPending
default:
return CIStatusError
}
}
// IsDone returns true if in a completed state.
func (status CIStatus) IsDone() bool {
//nolint:exhaustive
switch status {
case CIStatusWaitingOnDeps,
CIStatusPending,
CIStatusRunning,
CIStatusBlocked:
return false
default:
return true
}
}
// IsFailed returns true if in a failed state.
func (status CIStatus) IsFailed() bool {
return status == CIStatusFailure ||
status == CIStatusKilled ||
status == CIStatusError
}
// List of all CIStatus values.
var ciStatuses = sortEnum([]CIStatus{
CIStatusSkipped,
CIStatusBlocked,
CIStatusDeclined,
CIStatusWaitingOnDeps,
CIStatusPending,
CIStatusRunning,
CIStatusSuccess,
CIStatusFailure,
CIStatusKilled,
CIStatusError,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/gitspace_settings.go | types/enum/gitspace_settings.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type GitspaceSettingsType string
var gitspaceSettingsTypes = []GitspaceSettingsType{
SettingsTypeGitspaceConfig, SettingsTypeInfraProvider,
}
func (GitspaceSettingsType) Enum() []any {
return toInterfaceSlice(gitspaceSettingsTypes)
}
const (
SettingsTypeGitspaceConfig GitspaceSettingsType = "gitspace_configuration"
SettingsTypeInfraProvider GitspaceSettingsType = "infra_provider"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/settings.go | types/enum/settings.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// SettingsScope defines the different scopes of a setting.
type SettingsScope string
func (SettingsScope) Enum() []any {
return toInterfaceSlice(GetAllSettingsScopes())
}
var (
// SettingsScopeSpace defines settings stored on a space level.
SettingsScopeSpace SettingsScope = "space"
// SettingsScopeRepo defines settings stored on a repo level.
SettingsScopeRepo SettingsScope = "repo"
// SettingsScopeSystem defines settings stored on a system.
SettingsScopeSystem SettingsScope = "system"
)
func GetAllSettingsScopes() []SettingsScope {
return []SettingsScope{
SettingsScopeSpace,
SettingsScopeRepo,
SettingsScopeSystem,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/infra_status.go | types/enum/infra_status.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type InfraStatus string
func (InfraStatus) Enum() []any {
return toInterfaceSlice(infraStatuses)
}
var infraStatuses = []InfraStatus{
InfraStatusPending,
InfraStatusProvisioned,
InfraStatusDestroyed,
InfraStatusUnknown,
InfraStatusError,
InfraStatusStopped,
}
const (
InfraStatusPending InfraStatus = "pending"
InfraStatusProvisioned InfraStatus = "provisioned"
InfraStatusStopped InfraStatus = "stopped"
InfraStatusDestroyed InfraStatus = "destroyed"
InfraStatusUnknown InfraStatus = "unknown"
InfraStatusError InfraStatus = "error"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/scm.go | types/enum/scm.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// ScmType defines the different SCM types supported for CI.
type ScmType string
func (ScmType) Enum() []any { return toInterfaceSlice(scmTypes) }
var scmTypes = ([]ScmType{
ScmTypeGitness,
ScmTypeGithub,
ScmTypeGitlab,
ScmTypeUnknown,
})
const (
ScmTypeUnknown ScmType = "UNKNOWN"
ScmTypeGitness ScmType = "GITNESS"
ScmTypeGithub ScmType = "GITHUB"
ScmTypeGitlab ScmType = "GITLAB"
)
func AllSCMTypeStrings() []string {
result := make([]string, len(scmTypes))
for i, t := range scmTypes {
result[i] = string(t)
}
return result
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/gitspace_entity_type.go | types/enum/gitspace_entity_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type GitspaceEntityType string
func (GitspaceEntityType) Enum() []any { return toInterfaceSlice(gitspaceEntityTypes) }
var gitspaceEntityTypes = []GitspaceEntityType{
GitspaceEntityTypeGitspaceConfig,
GitspaceEntityTypeGitspaceInstance,
}
const (
GitspaceEntityTypeGitspaceConfig GitspaceEntityType = "gitspace_config"
GitspaceEntityTypeGitspaceInstance GitspaceEntityType = "gitspace_instance"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/pullreq.go | types/enum/pullreq.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
gitenum "github.com/harness/gitness/git/enum"
)
// PullReqState defines pull request state.
type PullReqState string
func (PullReqState) Enum() []any { return toInterfaceSlice(pullReqStates) }
func (s PullReqState) Sanitize() (PullReqState, bool) { return Sanitize(s, GetAllPullReqStates) }
func GetAllPullReqStates() ([]PullReqState, PullReqState) { return pullReqStates, "" }
// PullReqState enumeration.
const (
PullReqStateOpen PullReqState = "open"
PullReqStateMerged PullReqState = "merged"
PullReqStateClosed PullReqState = "closed"
)
var pullReqStates = sortEnum([]PullReqState{
PullReqStateOpen,
PullReqStateMerged,
PullReqStateClosed,
})
// PullReqSort defines pull request attribute that can be used for sorting.
type PullReqSort string
func (PullReqSort) Enum() []any { return toInterfaceSlice(pullReqSorts) }
func (s PullReqSort) Sanitize() (PullReqSort, bool) { return Sanitize(s, GetAllPullReqSorts) }
func GetAllPullReqSorts() ([]PullReqSort, PullReqSort) { return pullReqSorts, PullReqSortNumber }
// PullReqSort enumeration.
const (
PullReqSortNumber = "number"
PullReqSortCreated = "created"
PullReqSortEdited = "edited"
PullReqSortMerged = "merged"
PullReqSortUpdated = "updated"
)
var pullReqSorts = sortEnum([]PullReqSort{
PullReqSortNumber,
PullReqSortCreated,
PullReqSortEdited,
PullReqSortMerged,
PullReqSortUpdated,
})
// PullReqActivityType defines pull request activity message type.
// Essentially, the Type determines the structure of the pull request activity's Payload structure.
type PullReqActivityType string
func (PullReqActivityType) Enum() []any { return toInterfaceSlice(pullReqActivityTypes) }
func (t PullReqActivityType) Sanitize() (PullReqActivityType, bool) {
return Sanitize(t, GetAllPullReqActivityTypes)
}
func GetAllPullReqActivityTypes() ([]PullReqActivityType, PullReqActivityType) {
return pullReqActivityTypes, "" // No default value
}
// PullReqActivityType enumeration.
const (
PullReqActivityTypeComment PullReqActivityType = "comment"
PullReqActivityTypeCodeComment PullReqActivityType = "code-comment"
PullReqActivityTypeTitleChange PullReqActivityType = "title-change"
PullReqActivityTypeStateChange PullReqActivityType = "state-change"
PullReqActivityTypeReviewSubmit PullReqActivityType = "review-submit"
PullReqActivityTypeReviewerAdd PullReqActivityType = "reviewer-add"
PullReqActivityTypeUserGroupReviewerAdd PullReqActivityType = "user-group-reviewer-add"
PullReqActivityTypeReviewerDelete PullReqActivityType = "reviewer-delete"
PullReqActivityTypeUserGroupReviewerDelete PullReqActivityType = "user-group-reviewer-delete"
PullReqActivityTypeBranchUpdate PullReqActivityType = "branch-update"
PullReqActivityTypeBranchDelete PullReqActivityType = "branch-delete"
PullReqActivityTypeBranchRestore PullReqActivityType = "branch-restore"
PullReqActivityTypeTargetBranchChange PullReqActivityType = "target-branch-change"
PullReqActivityTypeMerge PullReqActivityType = "merge"
PullReqActivityTypeLabelModify PullReqActivityType = "label-modify"
PullReqActivityTypeNonUniqueMergeBase PullReqActivityType = "non-unique-merge-base"
)
var pullReqActivityTypes = sortEnum([]PullReqActivityType{
PullReqActivityTypeComment,
PullReqActivityTypeCodeComment,
PullReqActivityTypeTitleChange,
PullReqActivityTypeStateChange,
PullReqActivityTypeReviewSubmit,
PullReqActivityTypeReviewerAdd,
PullReqActivityTypeUserGroupReviewerAdd,
PullReqActivityTypeReviewerDelete,
PullReqActivityTypeUserGroupReviewerDelete,
PullReqActivityTypeBranchUpdate,
PullReqActivityTypeBranchDelete,
PullReqActivityTypeBranchRestore,
PullReqActivityTypeTargetBranchChange,
PullReqActivityTypeMerge,
PullReqActivityTypeLabelModify,
})
// PullReqActivityKind defines kind of pull request activity system message.
// Kind defines the source of the pull request activity entry:
// Whether it's generated by the system, it's a user comment or a part of code review.
type PullReqActivityKind string
func (PullReqActivityKind) Enum() []any { return toInterfaceSlice(pullReqActivityKinds) }
func (k PullReqActivityKind) Sanitize() (PullReqActivityKind, bool) {
return Sanitize(k, GetAllPullReqActivityKinds)
}
func GetAllPullReqActivityKinds() ([]PullReqActivityKind, PullReqActivityKind) {
return pullReqActivityKinds, "" // No default value
}
// PullReqActivityKind enumeration.
const (
PullReqActivityKindSystem PullReqActivityKind = "system"
PullReqActivityKindComment PullReqActivityKind = "comment"
PullReqActivityKindChangeComment PullReqActivityKind = "change-comment"
)
var pullReqActivityKinds = sortEnum([]PullReqActivityKind{
PullReqActivityKindSystem,
PullReqActivityKindComment,
PullReqActivityKindChangeComment,
})
// PullReqCommentStatus defines status of a pull request comment.
type PullReqCommentStatus string
func (PullReqCommentStatus) Enum() []any { return toInterfaceSlice(pullReqCommentStatuses) }
func (s PullReqCommentStatus) Sanitize() (PullReqCommentStatus, bool) {
return Sanitize(s, GetAllPullReqCommentStatuses)
}
func GetAllPullReqCommentStatuses() ([]PullReqCommentStatus, PullReqCommentStatus) {
return pullReqCommentStatuses, "" // No default value
}
// PullReqCommentStatus enumeration.
const (
PullReqCommentStatusActive PullReqCommentStatus = "active"
PullReqCommentStatusResolved PullReqCommentStatus = "resolved"
)
var pullReqCommentStatuses = sortEnum([]PullReqCommentStatus{
PullReqCommentStatusActive,
PullReqCommentStatusResolved,
})
// PullReqReviewDecision defines state of a pull request review.
type PullReqReviewDecision string
func (PullReqReviewDecision) Enum() []any {
return toInterfaceSlice(pullReqReviewDecisions)
}
func (decision PullReqReviewDecision) Sanitize() (PullReqReviewDecision, bool) {
return Sanitize(decision, GetAllPullReqReviewDecisions)
}
func GetAllPullReqReviewDecisions() ([]PullReqReviewDecision, PullReqReviewDecision) {
return pullReqReviewDecisions, "" // No default value
}
// PullReqReviewDecision enumeration.
const (
PullReqReviewDecisionPending PullReqReviewDecision = "pending"
PullReqReviewDecisionReviewed PullReqReviewDecision = "reviewed"
PullReqReviewDecisionApproved PullReqReviewDecision = "approved"
PullReqReviewDecisionChangeReq PullReqReviewDecision = "changereq"
)
var pullReqReviewDecisions = sortEnum([]PullReqReviewDecision{
PullReqReviewDecisionPending,
PullReqReviewDecisionReviewed,
PullReqReviewDecisionApproved,
PullReqReviewDecisionChangeReq,
})
// PullReqReviewerType defines type of a pull request reviewer.
type PullReqReviewerType string
func (PullReqReviewerType) Enum() []any { return toInterfaceSlice(pullReqReviewerTypes) }
func (reviewerType PullReqReviewerType) Sanitize() (PullReqReviewerType, bool) {
return Sanitize(reviewerType, GetAllPullReqReviewerTypes)
}
func GetAllPullReqReviewerTypes() ([]PullReqReviewerType, PullReqReviewerType) {
return pullReqReviewerTypes, "" // No default value
}
// PullReqReviewerType enumeration.
const (
PullReqReviewerTypeRequested PullReqReviewerType = "requested"
PullReqReviewerTypeAssigned PullReqReviewerType = "assigned"
PullReqReviewerTypeSelfAssigned PullReqReviewerType = "self_assigned"
// Used when adding reviewers on PR creation based on CODEOWNERS file or rules.
PullReqReviewerTypeCodeOwners PullReqReviewerType = "code_owners"
PullReqReviewerTypeDefault PullReqReviewerType = "default"
)
var pullReqReviewerTypes = sortEnum([]PullReqReviewerType{
PullReqReviewerTypeRequested,
PullReqReviewerTypeAssigned,
PullReqReviewerTypeSelfAssigned,
PullReqReviewerTypeCodeOwners,
PullReqReviewerTypeDefault,
})
type MergeMethod gitenum.MergeMethod
// MergeMethod enumeration.
const (
MergeMethodMerge = MergeMethod(gitenum.MergeMethodMerge)
MergeMethodSquash = MergeMethod(gitenum.MergeMethodSquash)
MergeMethodRebase = MergeMethod(gitenum.MergeMethodRebase)
MergeMethodFastForward = MergeMethod(gitenum.MergeMethodFastForward)
)
var MergeMethods = sortEnum([]MergeMethod{
MergeMethodMerge,
MergeMethodSquash,
MergeMethodRebase,
MergeMethodFastForward,
})
func (MergeMethod) Enum() []any { return toInterfaceSlice(MergeMethods) }
func (m MergeMethod) Sanitize() (MergeMethod, bool) {
s, ok := gitenum.MergeMethod(m).Sanitize()
return MergeMethod(s), ok
}
type MergeCheckStatus string
const (
// MergeCheckStatusUnchecked merge status has not been checked.
MergeCheckStatusUnchecked MergeCheckStatus = "unchecked"
// MergeCheckStatusConflict can’t merge into the target branch due to a potential conflict.
MergeCheckStatusConflict MergeCheckStatus = "conflict"
// MergeCheckStatusMergeable branch can merged cleanly into the target branch.
MergeCheckStatusMergeable MergeCheckStatus = "mergeable"
)
type PullReqLabelActivityType string
func (PullReqLabelActivityType) Enum() []any { return toInterfaceSlice(LabelActivityTypes) }
func (t PullReqLabelActivityType) Sanitize() (PullReqLabelActivityType, bool) {
return Sanitize(t, GetAllLabelActivityTypes)
}
func GetAllLabelActivityTypes() ([]PullReqLabelActivityType, PullReqLabelActivityType) {
return LabelActivityTypes, LabelActivityNoop
}
const (
LabelActivityAssign PullReqLabelActivityType = "assign"
LabelActivityUnassign PullReqLabelActivityType = "unassign"
LabelActivityReassign PullReqLabelActivityType = "reassign"
LabelActivityNoop PullReqLabelActivityType = "noop"
)
var LabelActivityTypes = sortEnum([]PullReqLabelActivityType{
LabelActivityAssign,
LabelActivityUnassign,
LabelActivityReassign,
LabelActivityNoop,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/space.go | types/enum/space.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "strings"
// SpaceAttr defines space attributes that can be used for sorting and filtering.
type SpaceAttr int
// Order enumeration.
const (
SpaceAttrNone SpaceAttr = iota
// TODO [CODE-1363]: remove after identifier migration.
SpaceAttrUID
SpaceAttrIdentifier
SpaceAttrCreated
SpaceAttrUpdated
SpaceAttrDeleted
)
// ParseSpaceAttr parses the space attribute string
// and returns the equivalent enumeration.
func ParseSpaceAttr(s string) SpaceAttr {
switch strings.ToLower(s) {
// TODO [CODE-1363]: remove after identifier migration.
case uid:
return SpaceAttrUID
case identifier:
return SpaceAttrIdentifier
case created, createdAt:
return SpaceAttrCreated
case updated, updatedAt:
return SpaceAttrUpdated
case deleted, deletedAt:
return SpaceAttrDeleted
default:
return SpaceAttrNone
}
}
// String returns the string representation of the attribute.
func (a SpaceAttr) String() string {
switch a {
// TODO [CODE-1363]: remove after identifier migration.
case SpaceAttrUID:
return uid
case SpaceAttrIdentifier:
return identifier
case SpaceAttrCreated:
return created
case SpaceAttrUpdated:
return updated
case SpaceAttrDeleted:
return deleted
case SpaceAttrNone:
return ""
default:
return undefined
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/public_key.go | types/enum/public_key.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type PublicKeyScheme string
const (
PublicKeySchemeSSH PublicKeyScheme = "ssh"
PublicKeySchemePGP PublicKeyScheme = "pgp"
)
var publicKeySchemes = sortEnum([]PublicKeyScheme{
PublicKeySchemeSSH, PublicKeySchemePGP,
})
func (PublicKeyScheme) Enum() []any { return toInterfaceSlice(publicKeySchemes) }
func (s PublicKeyScheme) Sanitize() (PublicKeyScheme, bool) {
return Sanitize(s, GetAllPublicKeySchemes)
}
func GetAllPublicKeySchemes() ([]PublicKeyScheme, PublicKeyScheme) {
return publicKeySchemes, PublicKeySchemeSSH
}
// PublicKeyUsage represents usage type of public key.
type PublicKeyUsage string
// PublicKeyUsage enumeration.
const (
PublicKeyUsageAuth PublicKeyUsage = "auth"
PublicKeyUsageSign PublicKeyUsage = "sign"
PublicKeyUsageAuthSign PublicKeyUsage = "auth_or_sign"
)
var publicKeyTypes = sortEnum([]PublicKeyUsage{
PublicKeyUsageAuth, PublicKeyUsageSign, PublicKeyUsageAuthSign,
})
func (PublicKeyUsage) Enum() []any { return toInterfaceSlice(publicKeyTypes) }
func (s PublicKeyUsage) Sanitize() (PublicKeyUsage, bool) {
return Sanitize(s, GetAllPublicKeyUsages)
}
func GetAllPublicKeyUsages() ([]PublicKeyUsage, PublicKeyUsage) {
return publicKeyTypes, PublicKeyUsageAuth
}
// PublicKeySort is used to specify sorting of public keys.
type PublicKeySort string
// PublicKeySort enumeration.
const (
PublicKeySortCreated PublicKeySort = "created"
PublicKeySortIdentifier PublicKeySort = "identifier"
)
var publicKeySorts = sortEnum([]PublicKeySort{
PublicKeySortCreated,
PublicKeySortIdentifier,
})
func (PublicKeySort) Enum() []any { return toInterfaceSlice(publicKeySorts) }
func (s PublicKeySort) Sanitize() (PublicKeySort, bool) { return Sanitize(s, GetAllPublicKeySorts) }
func GetAllPublicKeySorts() ([]PublicKeySort, PublicKeySort) {
return publicKeySorts, PublicKeySortCreated
}
// RevocationReason is the reason why a public key has been revoked.
type RevocationReason string
// RevocationReason enumeration.
const (
RevocationReasonUnknown RevocationReason = "unknown"
RevocationReasonSuperseded RevocationReason = "superseded"
RevocationReasonRetired RevocationReason = "retired"
RevocationReasonCompromised RevocationReason = "compromised"
)
var revocationReasons = sortEnum([]RevocationReason{
RevocationReasonUnknown,
RevocationReasonSuperseded,
RevocationReasonRetired,
RevocationReasonCompromised,
})
func (RevocationReason) Enum() []any { return toInterfaceSlice(revocationReasons) }
func (s RevocationReason) Sanitize() (RevocationReason, bool) {
return Sanitize(s, GetAllRevocationReasons)
}
func GetAllRevocationReasons() ([]RevocationReason, RevocationReason) {
return revocationReasons, ""
}
// GitSignatureResult is outcome of a git object's signature verification.
type GitSignatureResult string
const (
// GitSignatureInvalid is used when the signature itself is malformed.
// Shouldn't be stored to the DB.
GitSignatureInvalid GitSignatureResult = "invalid"
// GitSignatureUnsupported is used when the system is unable to verify the signature
// because the signature version is not supported by the system.
// Shouldn't be stored to the DB.
GitSignatureUnsupported GitSignatureResult = "unsupported"
// GitSignatureUnverified is used when the signer is not in the DB or
// when the key to verify the signature is missing.
// Shouldn't be stored to the DB.
GitSignatureUnverified GitSignatureResult = "unverified"
// GitSignatureGood is used when the signature is cryptographically valid for the signed object.
GitSignatureGood GitSignatureResult = "good"
// GitSignatureBad is used when the signature is bad (doesn’t match the object contents).
GitSignatureBad GitSignatureResult = "bad"
// GitSignatureKeyExpired is used when the content's timestamp is not within the key's validity period.
GitSignatureKeyExpired GitSignatureResult = "key_expired"
// GitSignatureRevoked is used when the signature is valid, but is signed with a revoked key.
GitSignatureRevoked GitSignatureResult = "revoked"
)
var gitSignatureResults = sortEnum([]GitSignatureResult{
GitSignatureInvalid,
GitSignatureUnsupported,
GitSignatureUnverified,
GitSignatureGood,
GitSignatureBad,
GitSignatureKeyExpired,
GitSignatureRevoked,
})
func (GitSignatureResult) Enum() []any {
return toInterfaceSlice(gitSignatureResults)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/repo.go | types/enum/repo.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"strings"
)
// RepoAttr defines repo attributes that can be used for sorting and filtering.
type RepoAttr int
// RepoAttr enumeration.
const (
RepoAttrNone RepoAttr = iota
// TODO [CODE-1363]: remove after identifier migration.
RepoAttrUID
RepoAttrIdentifier
RepoAttrCreated
RepoAttrUpdated
RepoAttrDeleted
RepoAttrLastGITPush
)
// ParseRepoAttr parses the repo attribute string
// and returns the equivalent enumeration.
func ParseRepoAttr(s string) RepoAttr {
switch strings.ToLower(s) {
// TODO [CODE-1363]: remove after identifier migration.
case uid:
return RepoAttrUID
case identifier:
return RepoAttrIdentifier
case created, createdAt:
return RepoAttrCreated
case updated, updatedAt:
return RepoAttrUpdated
case deleted, deletedAt:
return RepoAttrDeleted
case lastGITPush:
return RepoAttrLastGITPush
default:
return RepoAttrNone
}
}
// String returns the string representation of the attribute.
func (a RepoAttr) String() string {
switch a {
// TODO [CODE-1363]: remove after identifier migration.
case RepoAttrUID:
return uid
case RepoAttrIdentifier:
return identifier
case RepoAttrCreated:
return created
case RepoAttrUpdated:
return updated
case RepoAttrDeleted:
return deleted
case RepoAttrLastGITPush:
return lastGITPush
case RepoAttrNone:
return ""
default:
return undefined
}
}
// RepoState defines repo state.
type RepoState int
// RepoState enumeration.
const (
RepoStateActive RepoState = iota
RepoStateGitImport
RepoStateMigrateGitPush
RepoStateMigrateDataImport
RepoStateArchived
)
// String returns the string representation of the RepoState.
func (state RepoState) String() string {
switch state {
case RepoStateActive:
return "active"
case RepoStateGitImport:
return "git-import"
case RepoStateMigrateGitPush:
return "migrate-git-push"
case RepoStateMigrateDataImport:
return "migrate-data-import"
case RepoStateArchived:
return "archived"
default:
return undefined
}
}
// RepoType defines repo type.
type RepoType string
// RepoType enumeration.
const (
RepoTypeNormal RepoType = ""
RepoTypeLinked RepoType = "linked"
)
// String returns the string representation of the RepoType.
func (t RepoType) String() string {
switch t {
case RepoTypeNormal:
return ""
case RepoTypeLinked:
return "linked"
default:
return undefined
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/encoding_test.go | types/enum/encoding_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"reflect"
"testing"
)
func TestContentEncodingTypeConstants(t *testing.T) {
tests := []struct {
name string
encoding ContentEncodingType
expected string
}{
{
name: "UTF8 encoding",
encoding: ContentEncodingTypeUTF8,
expected: "utf8",
},
{
name: "Base64 encoding",
encoding: ContentEncodingTypeBase64,
expected: "base64",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if string(tt.encoding) != tt.expected {
t.Errorf("Expected %s to be %q, got %q", tt.name, tt.expected, string(tt.encoding))
}
})
}
}
func TestContentEncodingTypeString(t *testing.T) {
tests := []struct {
name string
encoding ContentEncodingType
expected string
}{
{
name: "UTF8 string representation",
encoding: ContentEncodingTypeUTF8,
expected: "utf8",
},
{
name: "Base64 string representation",
encoding: ContentEncodingTypeBase64,
expected: "base64",
},
{
name: "Custom encoding",
encoding: ContentEncodingType("custom"),
expected: "custom",
},
{
name: "Empty encoding",
encoding: ContentEncodingType(""),
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := string(tt.encoding)
if result != tt.expected {
t.Errorf("Expected string representation to be %q, got %q", tt.expected, result)
}
})
}
}
func TestContentEncodingTypeEnum(t *testing.T) {
// Test that Enum() returns the expected values
encoding := ContentEncodingTypeUTF8
enumValues := encoding.Enum()
// Should return 2 values
if len(enumValues) != 2 {
t.Errorf("Expected Enum() to return 2 values, got %d", len(enumValues))
}
// Check that the values are correct
expectedValues := []any{
ContentEncodingTypeBase64, // sorted order: base64 comes before utf8
ContentEncodingTypeUTF8,
}
if !reflect.DeepEqual(enumValues, expectedValues) {
t.Errorf("Expected Enum() to return %v, got %v", expectedValues, enumValues)
}
}
func TestContentEncodingTypeEnumSorted(t *testing.T) {
// Test that the enum values are sorted
encoding := ContentEncodingTypeUTF8
enumValues := encoding.Enum()
// Convert back to ContentEncodingType for comparison
var encodingTypes []ContentEncodingType
for _, v := range enumValues {
if enc, ok := v.(ContentEncodingType); ok {
encodingTypes = append(encodingTypes, enc)
}
}
// Check that they are in sorted order
if len(encodingTypes) >= 2 {
if encodingTypes[0] > encodingTypes[1] {
t.Errorf("Expected enum values to be sorted, but %q > %q", encodingTypes[0], encodingTypes[1])
}
}
}
func TestContentEncodingTypeComparison(t *testing.T) {
// Test string comparison
if ContentEncodingTypeUTF8 == ContentEncodingTypeBase64 {
t.Error("Expected UTF8 and Base64 encodings to be different")
}
if ContentEncodingTypeUTF8 < ContentEncodingTypeBase64 {
t.Error("Expected UTF8 to be greater than Base64 in string comparison")
}
// Test equality
utf8Copy := ContentEncodingType("utf8")
if ContentEncodingTypeUTF8 != utf8Copy {
t.Error("Expected identical encoding types to be equal")
}
}
func TestContentEncodingTypeZeroValue(t *testing.T) {
var encoding ContentEncodingType
if encoding != "" {
t.Errorf("Expected zero value of ContentEncodingType to be empty string, got %q", encoding)
}
}
func TestContentEncodingTypeConversion(t *testing.T) {
// Test conversion from string
str := "utf8"
encoding := ContentEncodingType(str)
if encoding != ContentEncodingTypeUTF8 {
t.Errorf("Expected conversion from string %q to give %q, got %q", str, ContentEncodingTypeUTF8, encoding)
}
// Test conversion to string
result := string(ContentEncodingTypeBase64)
if result != "base64" {
t.Errorf("Expected conversion to string to give %q, got %q", "base64", result)
}
}
func TestContentEncodingTypeValidation(t *testing.T) {
// Test validation against known values
validEncodings := []ContentEncodingType{
ContentEncodingTypeUTF8,
ContentEncodingTypeBase64,
}
for _, encoding := range validEncodings {
t.Run(string(encoding), func(t *testing.T) {
// Check that the encoding is in the enum
enumValues := encoding.Enum()
found := false
for _, v := range enumValues {
if v == encoding {
found = true
break
}
}
if !found {
t.Errorf("Expected %q to be found in enum values", encoding)
}
})
}
}
func TestContentEncodingTypeInvalidValues(t *testing.T) {
// Test with invalid/unknown encoding types
invalidEncodings := []ContentEncodingType{
ContentEncodingType("invalid"),
ContentEncodingType("unknown"),
ContentEncodingType("UTF8"), // case sensitive
ContentEncodingType("BASE64"), // case sensitive
ContentEncodingType("utf-8"), // different format
ContentEncodingType("base-64"), // different format
}
for _, encoding := range invalidEncodings {
t.Run(string(encoding), func(t *testing.T) {
// These should not be in the enum
enumValues := encoding.Enum()
found := false
for _, v := range enumValues {
if v == encoding {
found = true
break
}
}
if found {
t.Errorf("Expected %q to NOT be found in enum values", encoding)
}
})
}
}
// Benchmark tests.
func BenchmarkContentEncodingTypeString(b *testing.B) {
encoding := ContentEncodingTypeUTF8
for b.Loop() {
_ = string(encoding)
}
}
func BenchmarkContentEncodingTypeEnum(b *testing.B) {
encoding := ContentEncodingTypeUTF8
for b.Loop() {
_ = encoding.Enum()
}
}
func BenchmarkContentEncodingTypeComparison(b *testing.B) {
encoding1 := ContentEncodingTypeUTF8
encoding2 := ContentEncodingTypeBase64
for b.Loop() {
_ = encoding1 == encoding2
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/resource.go | types/enum/resource.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// ResourceType represents the different types of resources that can be guarded with permissions.
type ResourceType string
const (
ResourceTypeSpace ResourceType = "SPACE"
ResourceTypeRepo ResourceType = "REPOSITORY"
ResourceTypeUser ResourceType = "USER"
ResourceTypeServiceAccount ResourceType = "SERVICEACCOUNT"
ResourceTypeService ResourceType = "SERVICE"
ResourceTypePipeline ResourceType = "PIPELINE"
ResourceTypeSecret ResourceType = "SECRET"
ResourceTypeConnector ResourceType = "CONNECTOR"
ResourceTypeTemplate ResourceType = "TEMPLATE"
ResourceTypeGitspace ResourceType = "GITSPACE"
ResourceTypeInfraProvider ResourceType = "INFRAPROVIDER"
ResourceTypeRegistry ResourceType = "REGISTRY"
)
func (ResourceType) Enum() []any {
return toInterfaceSlice(resourceTypes)
}
func (r ResourceType) Sanitize() (ResourceType, bool) { return Sanitize(r, GetAllResourceTypes) }
func GetAllResourceTypes() ([]ResourceType, ResourceType) {
return resourceTypes, ""
}
// All valid resource types.
var resourceTypes = sortEnum([]ResourceType{
ResourceTypeSpace,
ResourceTypeRepo,
ResourceTypeUser,
ResourceTypeServiceAccount,
ResourceTypeService,
ResourceTypePipeline,
ResourceTypeSecret,
ResourceTypeConnector,
ResourceTypeTemplate,
ResourceTypeGitspace,
ResourceTypeInfraProvider,
ResourceTypeRegistry,
})
// ParentResourceType defines the different types of parent resources.
type ParentResourceType string
func (ParentResourceType) Enum() []any {
return toInterfaceSlice(GetAllParentResourceTypes())
}
var (
ParentResourceTypeSpace ParentResourceType = "space"
ParentResourceTypeRepo ParentResourceType = "repo"
)
func GetAllParentResourceTypes() []ParentResourceType {
return []ParentResourceType{
ParentResourceTypeSpace,
ParentResourceTypeRepo,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/trigger_actions.go | types/enum/trigger_actions.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// TriggerAction defines the different actions on triggers will fire.
type TriggerAction string
// These are similar to enums defined in webhook enum but can diverge
// as these are different entities.
const (
// TriggerActionBranchCreated gets triggered when a branch gets created.
TriggerActionBranchCreated TriggerAction = "branch_created"
// TriggerActionBranchUpdated gets triggered when a branch gets updated.
TriggerActionBranchUpdated TriggerAction = "branch_updated"
// TriggerActionTagCreated gets triggered when a tag gets created.
TriggerActionTagCreated TriggerAction = "tag_created"
// TriggerActionTagUpdated gets triggered when a tag gets updated.
TriggerActionTagUpdated TriggerAction = "tag_updated"
// TriggerActionPullReqCreated gets triggered when a pull request gets created.
TriggerActionPullReqCreated TriggerAction = "pullreq_created"
// TriggerActionPullReqReopened gets triggered when a pull request gets reopened.
TriggerActionPullReqReopened TriggerAction = "pullreq_reopened"
// TriggerActionPullReqBranchUpdated gets triggered when a pull request source branch gets updated.
TriggerActionPullReqBranchUpdated TriggerAction = "pullreq_branch_updated"
// TriggerActionPullReqClosed gets triggered when a pull request is closed.
TriggerActionPullReqClosed TriggerAction = "pullreq_closed"
// TriggerActionPullReqMerged gets triggered when a pull request is merged.
TriggerActionPullReqMerged TriggerAction = "pullreq_merged"
)
func (TriggerAction) Enum() []any { return toInterfaceSlice(triggerActions) }
func (t TriggerAction) Sanitize() (TriggerAction, bool) { return Sanitize(t, GetAllTriggerActions) }
func (t TriggerAction) GetTriggerEvent() TriggerEvent {
if t == TriggerActionPullReqCreated ||
t == TriggerActionPullReqBranchUpdated ||
t == TriggerActionPullReqReopened ||
t == TriggerActionPullReqClosed ||
t == TriggerActionPullReqMerged {
return TriggerEventPullRequest
}
if t == TriggerActionTagCreated || t == TriggerActionTagUpdated {
return TriggerEventTag
}
if t == "" {
return TriggerEventManual
}
return TriggerEventPush
}
func GetAllTriggerActions() ([]TriggerAction, TriggerAction) {
return triggerActions, "" // No default value
}
var triggerActions = sortEnum([]TriggerAction{
TriggerActionBranchCreated,
TriggerActionBranchUpdated,
TriggerActionTagCreated,
TriggerActionTagUpdated,
TriggerActionPullReqCreated,
TriggerActionPullReqReopened,
TriggerActionPullReqBranchUpdated,
TriggerActionPullReqClosed,
TriggerActionPullReqMerged,
})
// Trigger types.
const (
TriggerHook = "@hook"
TriggerCron = "@cron"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/gitspace_code_repo_type.go | types/enum/gitspace_code_repo_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"encoding/json"
"fmt"
)
type GitspaceCodeRepoType string
func (p GitspaceCodeRepoType) Enum() []any {
return toInterfaceSlice(codeRepoTypes)
}
var codeRepoTypes = []GitspaceCodeRepoType{
CodeRepoTypeGithub,
CodeRepoTypeGitlab,
CodeRepoTypeHarnessCode,
CodeRepoTypeBitbucket,
CodeRepoTypeUnknown,
CodeRepoTypeGitness,
CodeRepoTypeGitlabOnPrem,
CodeRepoTypeBitbucketServer,
CodeRepoTypeGithubEnterprise,
}
const (
CodeRepoTypeGithub GitspaceCodeRepoType = "github"
CodeRepoTypeGitlab GitspaceCodeRepoType = "gitlab"
CodeRepoTypeGitness GitspaceCodeRepoType = "gitness"
CodeRepoTypeHarnessCode GitspaceCodeRepoType = "harness_code"
CodeRepoTypeBitbucket GitspaceCodeRepoType = "bitbucket"
CodeRepoTypeUnknown GitspaceCodeRepoType = "unknown"
CodeRepoTypeGitlabOnPrem GitspaceCodeRepoType = "gitlab_on_prem"
CodeRepoTypeBitbucketServer GitspaceCodeRepoType = "bitbucket_server"
CodeRepoTypeGithubEnterprise GitspaceCodeRepoType = "github_enterprise"
)
func (p *GitspaceCodeRepoType) IsOnPrem() bool {
if p == nil {
return false
}
return *p == CodeRepoTypeGitlabOnPrem || *p == CodeRepoTypeBitbucketServer || *p == CodeRepoTypeGithubEnterprise
}
func (p *GitspaceCodeRepoType) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
if s == "" {
*p = ""
return nil
}
for _, v := range codeRepoTypes {
if GitspaceCodeRepoType(s) == v {
*p = v
return nil
}
}
return fmt.Errorf("invalid GitspaceCodeRepoType: %s", s)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/public_resource.go | types/enum/public_resource.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// PublicResourceType defines the type of the public resource.
type PublicResourceType string
func (PublicResourceType) Enum() []any {
return toInterfaceSlice(GetAllPublicResourceTypes())
}
const (
PublicResourceTypeRepo PublicResourceType = "repository"
PublicResourceTypeSpace PublicResourceType = "space"
PublicResourceTypeRegistry PublicResourceType = "registry"
)
func GetAllPublicResourceTypes() []PublicResourceType {
return []PublicResourceType{
PublicResourceTypeRepo,
PublicResourceTypeSpace,
PublicResourceTypeRegistry,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/ai_agent.go | types/enum/ai_agent.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"encoding/json"
"fmt"
)
type AIAgent string
func (a AIAgent) Enum() []any {
return toInterfaceSlice(aiAgentTypes)
}
func (a AIAgent) String() string {
return string(a)
}
var aiAgentTypes = []AIAgent{
AIAgentClaudeCode,
}
const (
AIAgentClaudeCode AIAgent = "claude-code"
)
func (a *AIAgent) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
if str == "" {
*a = ""
return nil
}
for _, validType := range aiAgentTypes {
if AIAgent(str) == validType {
*a = validType
return nil
}
}
return fmt.Errorf("invalid AI agent type: %s", str)
}
func (a AIAgent) Sanitize() (AIAgent, bool) {
return Sanitize(a, GetAllAIAgents)
}
func GetAllAIAgents() ([]AIAgent, AIAgent) {
return aiAgentTypes, ""
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/gitspace_access_type.go | types/enum/gitspace_access_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type GitspaceAccessType string
func (GitspaceAccessType) Enum() []any { return toInterfaceSlice(gitspaceAccessTypes) }
var gitspaceAccessTypes = []GitspaceAccessType{
GitspaceAccessTypeJWTToken, GitspaceAccessTypeUserCredentials, GitspaceAccessTypeSSHKey,
}
const (
GitspaceAccessTypeJWTToken GitspaceAccessType = "jwt_token"
GitspaceAccessTypeUserCredentials GitspaceAccessType = "user_credentials"
GitspaceAccessTypeSSHKey GitspaceAccessType = "ssh_key"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/infra_event.go | types/enum/infra_event.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type InfraEvent string
func (InfraEvent) Enum() []any {
return toInterfaceSlice(infraEvents)
}
var infraEvents = []InfraEvent{
InfraEventProvision, InfraEventStop, InfraEventDeprovision, InfraEventCleanup,
}
const (
InfraEventProvision InfraEvent = "provision"
InfraEventStop InfraEvent = "stop"
InfraEventCleanup InfraEvent = "cleanup"
InfraEventDeprovision InfraEvent = "deprovision"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/encoding.go | types/enum/encoding.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// ContentEncodingType describes the encoding of content.
type ContentEncodingType string
const (
// ContentEncodingTypeUTF8 describes utf-8 encoded content.
ContentEncodingTypeUTF8 ContentEncodingType = "utf8"
// ContentEncodingTypeBase64 describes base64 encoded content.
ContentEncodingTypeBase64 ContentEncodingType = "base64"
)
func (ContentEncodingType) Enum() []any { return toInterfaceSlice(contentEncodingTypes) }
var contentEncodingTypes = sortEnum([]ContentEncodingType{
ContentEncodingTypeUTF8,
ContentEncodingTypeBase64,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/gitspace.go | types/enum/gitspace.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"strings"
)
// GitspaceSort represents gitspace sort order.
type GitspaceSort string
// GitspaceSort enumeration.
const (
GitspaceSortLastUsed GitspaceSort = lastUsed
GitspaceSortCreated GitspaceSort = created
GitspaceSortLastActivated GitspaceSort = lastActivated
)
var GitspaceSorts = sortEnum([]GitspaceSort{
GitspaceSortLastUsed,
GitspaceSortCreated,
GitspaceSortLastActivated,
})
func (GitspaceSort) Enum() []any { return toInterfaceSlice(GitspaceSorts) }
// ParseGitspaceSort parses the gitspace sort attribute string
// and returns the equivalent enumeration.
func ParseGitspaceSort(s string) GitspaceSort {
switch strings.ToLower(s) {
case lastUsed:
return GitspaceSortLastUsed
case created, createdAt:
return GitspaceSortCreated
case lastActivated:
return GitspaceSortLastActivated
default:
return GitspaceSortLastActivated
}
}
type GitspaceOwner string
var GitspaceOwners = sortEnum([]GitspaceOwner{
GitspaceOwnerSelf,
GitspaceOwnerAll,
})
const (
GitspaceOwnerSelf GitspaceOwner = "self"
GitspaceOwnerAll GitspaceOwner = "all"
)
func (GitspaceOwner) Enum() []any { return toInterfaceSlice(GitspaceOwners) }
// ParseGitspaceOwner parses the gitspace owner attribute string
// and returns the equivalent enumeration.
func ParseGitspaceOwner(s string) GitspaceOwner {
switch strings.ToLower(s) {
case string(GitspaceOwnerSelf):
return GitspaceOwnerSelf
case string(GitspaceOwnerAll):
return GitspaceOwnerAll
default:
return GitspaceOwnerSelf
}
}
type GitspaceFilterState string
func (GitspaceFilterState) Enum() []any { return toInterfaceSlice(GitspaceFilterStates) }
func (s GitspaceFilterState) Sanitize() (GitspaceFilterState, bool) {
return Sanitize(s, GetAllGitspaceFilterState)
}
func GetAllGitspaceFilterState() ([]GitspaceFilterState, GitspaceFilterState) {
return GitspaceFilterStates, ""
}
const (
GitspaceFilterStateRunning GitspaceFilterState = "running"
GitspaceFilterStateStopped GitspaceFilterState = "stopped"
GitspaceFilterStateError GitspaceFilterState = "error"
)
var GitspaceFilterStates = sortEnum([]GitspaceFilterState{
GitspaceFilterStateRunning,
GitspaceFilterStateStopped,
GitspaceFilterStateError,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/gitspace_instance_state_type.go | types/enum/gitspace_instance_state_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type GitspaceInstanceStateType string
func (GitspaceInstanceStateType) Enum() []any {
return toInterfaceSlice(gitspaceInstanceStateTypes)
}
var gitspaceInstanceStateTypes = []GitspaceInstanceStateType{
GitspaceInstanceStateRunning,
GitspaceInstanceStateUninitialized,
GitspaceInstanceStateUnknown,
GitspaceInstanceStateError,
GitspaceInstanceStateDeleted,
GitspaceInstanceStateStarting,
GitspaceInstanceStateStopping,
GitSpaceInstanceStateCleaning,
GitspaceInstanceStateCleaned,
GitSpaceInstanceStateResetting,
GitspaceInstanceStatePendingCleanup,
}
const (
GitspaceInstanceStateRunning GitspaceInstanceStateType = "running"
GitspaceInstanceStateUninitialized GitspaceInstanceStateType = "uninitialized"
GitspaceInstanceStateUnknown GitspaceInstanceStateType = "unknown"
GitspaceInstanceStateError GitspaceInstanceStateType = "error"
GitspaceInstanceStateStopped GitspaceInstanceStateType = "stopped"
GitspaceInstanceStateDeleted GitspaceInstanceStateType = "deleted"
GitspaceInstanceStateCleaned GitspaceInstanceStateType = "cleaned"
GitspaceInstanceStatePendingCleanup GitspaceInstanceStateType = "pending_cleanup"
GitspaceInstanceStateStarting GitspaceInstanceStateType = "starting"
GitspaceInstanceStateStopping GitspaceInstanceStateType = "stopping"
GitSpaceInstanceStateCleaning GitspaceInstanceStateType = "cleaning"
GitSpaceInstanceStateResetting GitspaceInstanceStateType = "resetting"
)
func (g GitspaceInstanceStateType) IsFinalStatus() bool {
//nolint:exhaustive
switch g {
case GitspaceInstanceStateDeleted,
GitspaceInstanceStateError,
GitspaceInstanceStateCleaned:
return true
default:
return false
}
}
func (g GitspaceInstanceStateType) IsBusyStatus() bool {
//nolint:exhaustive
switch g {
case GitspaceInstanceStateStarting,
GitspaceInstanceStateStopping,
GitSpaceInstanceStateCleaning,
GitSpaceInstanceStateResetting:
return true
default:
return false
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/ai_task_state.go | types/enum/ai_task_state.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type AITaskState string
func (AITaskState) Enum() []any {
return toInterfaceSlice(AITaskStateTypes)
}
var AITaskStateTypes = sortEnum([]AITaskState{
AITaskStateUninitialized,
AITaskStateRunning,
AITaskStateCompleted,
AITaskStateError,
})
const (
AITaskStateUninitialized AITaskState = "uninitialized"
AITaskStateRunning AITaskState = "running"
AITaskStateCompleted AITaskState = "completed"
AITaskStateError AITaskState = "error"
)
func (a AITaskState) IsFinalStatus() bool {
//nolint:exhaustive
switch a {
case AITaskStateCompleted,
AITaskStateError:
return true
default:
return false
}
}
func (a AITaskState) IsActiveStatus() bool {
//nolint:exhaustive
switch a {
case AITaskStateRunning:
return true
default:
return false
}
}
func (a AITaskState) Sanitize() (AITaskState, bool) {
return Sanitize(a, GetAllAITaskState)
}
func GetAllAITaskState() ([]AITaskState, AITaskState) {
return AITaskStateTypes, ""
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/user.go | types/enum/user.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "strings"
// UserAttr defines user attributes that can be
// used for sorting and filtering.
type UserAttr int
// Order enumeration.
const (
UserAttrNone UserAttr = iota
UserAttrUID
UserAttrName
UserAttrEmail
UserAttrAdmin
UserAttrCreated
UserAttrUpdated
)
// ParseUserAttr parses the user attribute string
// and returns the equivalent enumeration.
func ParseUserAttr(s string) UserAttr {
switch strings.ToLower(s) {
case uid:
return UserAttrUID
case name:
return UserAttrName
case email:
return UserAttrEmail
case admin:
return UserAttrAdmin
case created, createdAt:
return UserAttrCreated
case updated, updatedAt:
return UserAttrUpdated
default:
return UserAttrNone
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/rule.go | types/enum/rule.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"strings"
)
// RuleType represents rule type.
type RuleType string
// RuleType enumeration.
const (
RuleTypeBranch RuleType = "branch"
RuleTypeTag RuleType = "tag"
RuleTypePush RuleType = "push"
)
var ruleTypes = sortEnum([]RuleType{
RuleTypeBranch,
RuleTypeTag,
RuleTypePush,
})
func (RuleType) Enum() []any { return toInterfaceSlice(ruleTypes) }
func (s RuleType) Sanitize() (RuleType, bool) {
return Sanitize(s, GetAllRuleTypes)
}
func GetAllRuleTypes() ([]RuleType, RuleType) {
return ruleTypes, ""
}
// RuleState represents rule state.
type RuleState string
// RuleState enumeration.
const (
RuleStateActive RuleState = "active"
RuleStateMonitor RuleState = "monitor"
RuleStateDisabled RuleState = "disabled"
)
var ruleStates = sortEnum([]RuleState{
RuleStateActive,
RuleStateMonitor,
RuleStateDisabled,
})
func (RuleState) Enum() []any { return toInterfaceSlice(ruleStates) }
func (s RuleState) Sanitize() (RuleState, bool) {
return Sanitize(s, GetAllRuleStates)
}
func GetAllRuleStates() ([]RuleState, RuleState) {
return ruleStates, RuleStateActive
}
// RuleSort contains protection rule sorting options.
type RuleSort string
const (
// TODO [CODE-1363]: remove after identifier migration.
RuleSortUID RuleSort = uid
RuleSortIdentifier RuleSort = identifier
RuleSortCreated RuleSort = createdAt
RuleSortUpdated RuleSort = updatedAt
)
var ruleSorts = sortEnum([]RuleSort{
// TODO [CODE-1363]: remove after identifier migration.
RuleSortUID,
RuleSortIdentifier,
RuleSortCreated,
RuleSortUpdated,
})
func (RuleSort) Enum() []any { return toInterfaceSlice(ruleSorts) }
func (s RuleSort) Sanitize() (RuleSort, bool) {
return Sanitize(s, GetAllRuleSorts)
}
func GetAllRuleSorts() ([]RuleSort, RuleSort) {
return ruleSorts, RuleSortCreated
}
// ParseRuleSortAttr parses the protection rule sorting option.
func ParseRuleSortAttr(s string) RuleSort {
switch strings.ToLower(s) {
// TODO [CODE-1363]: remove after identifier migration.
case uid:
return RuleSortUID
case created, createdAt:
return RuleSortCreated
case updated, updatedAt:
return RuleSortUpdated
}
return RuleSortIdentifier
}
// RuleParent defines different types of parents of a rule.
type RuleParent string
func (RuleParent) Enum() []any { return toInterfaceSlice(RuleParents) }
const (
// RuleParentRepo describes a repo as Rule owner.
RuleParentRepo RuleParent = "repo"
// RuleParentSpace describes a space as Rule owner.
RuleParentSpace RuleParent = "space"
)
var RuleParents = sortEnum([]RuleParent{
RuleParentRepo,
RuleParentSpace,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/connector_type.go | types/enum/connector_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "fmt"
// ConnectorType represents the type of connector.
type ConnectorType string
const (
// ConnectorTypeGithub is a github connector.
ConnectorTypeGithub ConnectorType = "github"
)
func ParseConnectorType(s string) (ConnectorType, error) {
switch s {
case "github":
return ConnectorTypeGithub, nil
default:
return "", fmt.Errorf("unknown connector type provided: %s", s)
}
}
func (t ConnectorType) String() string {
switch t {
case ConnectorTypeGithub:
return "github"
default:
return undefined
}
}
func (t ConnectorType) IsSCM() bool {
switch t {
case ConnectorTypeGithub:
return true
default:
return false
}
}
func GetAllConnectorTypes() ([]ConnectorType, ConnectorType) {
return connectorTypes, "" // No default value
}
var connectorTypes = sortEnum([]ConnectorType{
ConnectorTypeGithub,
})
func (ConnectorType) Enum() []any { return toInterfaceSlice(connectorTypes) }
func (t ConnectorType) Sanitize() (ConnectorType, bool) { return Sanitize(t, GetAllConnectorTypes) }
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/codeowner_violation.go | types/enum/codeowner_violation.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type CodeOwnerViolationCode string
const (
// CodeOwnerViolationCodeUserNotFound occurs when user in codeowners file is not present.
CodeOwnerViolationCodeUserNotFound CodeOwnerViolationCode = "user_not_found"
// CodeOwnerViolationCodeUserGroupNotFound occurs when user group in codeowners file is not present.
CodeOwnerViolationCodeUserGroupNotFound CodeOwnerViolationCode = "user_group_not_found"
// CodeOwnerViolationCodePatternInvalid occurs when a pattern in codeowners file is incorrect.
CodeOwnerViolationCodePatternInvalid CodeOwnerViolationCode = "pattern_invalid"
// CodeOwnerViolationCodePatternEmpty occurs when a pattern in codeowners file is empty.
CodeOwnerViolationCodePatternEmpty CodeOwnerViolationCode = "pattern_empty"
// CodeOwnerViolationCodeUserPatternInvalid occurs when a pattern of user is invalid.
CodeOwnerViolationCodeUserPatternInvalid CodeOwnerViolationCode = "user_pattern_invalid"
)
func (CodeOwnerViolationCode) Enum() []any { return toInterfaceSlice(codeOwnerViolationCodes) }
var codeOwnerViolationCodes = sortEnum([]CodeOwnerViolationCode{
CodeOwnerViolationCodeUserNotFound,
CodeOwnerViolationCodePatternInvalid,
CodeOwnerViolationCodePatternEmpty,
CodeOwnerViolationCodeUserPatternInvalid,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/infra_provider_type.go | types/enum/infra_provider_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"encoding/json"
"fmt"
)
type InfraProviderType string
func (p InfraProviderType) Enum() []any {
return toInterfaceSlice(providerTypes)
}
var providerTypes = []InfraProviderType{
InfraProviderTypeDocker,
InfraProviderTypeHarnessGCP,
InfraProviderTypeHarnessCloud,
InfraProviderTypeHybridVMGCP,
InfraProviderTypeHybridVMAWS,
}
func AllInfraProviderTypes() []InfraProviderType {
return providerTypes
}
const (
InfraProviderTypeDocker InfraProviderType = "docker"
InfraProviderTypeHarnessGCP InfraProviderType = "harness_gcp"
InfraProviderTypeHarnessCloud InfraProviderType = "harness_cloud"
InfraProviderTypeHybridVMGCP InfraProviderType = "hybrid_vm_gcp"
InfraProviderTypeHybridVMAWS InfraProviderType = "hybrid_vm_aws"
)
func (p *InfraProviderType) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
if s == "" {
*p = ""
return nil
}
for _, v := range providerTypes {
if InfraProviderType(s) == v {
*p = v
return nil
}
}
return fmt.Errorf("invalid InfraProviderType: %s", s)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/permission.go | types/enum/permission.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// Permission represents the different types of permissions a principal can have.
type Permission string
const (
/*
----- SPACE -----
*/
PermissionSpaceView Permission = "space_view"
PermissionSpaceEdit Permission = "space_edit"
PermissionSpaceDelete Permission = "space_delete"
)
const (
/*
----- REPOSITORY -----
*/
PermissionRepoView Permission = "repo_view"
PermissionRepoCreate Permission = "repo_create"
PermissionRepoEdit Permission = "repo_edit"
PermissionRepoDelete Permission = "repo_delete"
PermissionRepoPush Permission = "repo_push"
PermissionRepoReview Permission = "repo_review"
PermissionRepoReportCommitCheck Permission = "repo_reportCommitCheck"
)
const (
/*
----- USER -----
*/
PermissionUserView Permission = "user_view"
PermissionUserEdit Permission = "user_edit"
PermissionUserDelete Permission = "user_delete"
PermissionUserEditAdmin Permission = "user_editAdmin"
)
const (
/*
----- SERVICE ACCOUNT -----
*/
PermissionServiceAccountView Permission = "serviceaccount_view"
PermissionServiceAccountEdit Permission = "serviceaccount_edit"
PermissionServiceAccountDelete Permission = "serviceaccount_delete"
)
const (
/*
----- SERVICE -----
*/
PermissionServiceView Permission = "service_view"
PermissionServiceEdit Permission = "service_edit"
PermissionServiceDelete Permission = "service_delete"
PermissionServiceEditAdmin Permission = "service_editAdmin"
)
const (
/*
----- PIPELINE -----
*/
PermissionPipelineView Permission = "pipeline_view"
PermissionPipelineEdit Permission = "pipeline_edit"
PermissionPipelineDelete Permission = "pipeline_delete"
PermissionPipelineExecute Permission = "pipeline_execute"
)
const (
/*
----- SECRET -----
*/
PermissionSecretView Permission = "secret_view"
PermissionSecretEdit Permission = "secret_edit"
PermissionSecretDelete Permission = "secret_delete"
PermissionSecretAccess Permission = "secret_access"
)
const (
/*
----- CONNECTOR -----
*/
PermissionConnectorView Permission = "connector_view"
PermissionConnectorEdit Permission = "connector_edit"
PermissionConnectorDelete Permission = "connector_delete"
PermissionConnectorAccess Permission = "connector_access"
)
const (
/*
----- TEMPLATE -----
*/
PermissionTemplateView Permission = "template_view"
PermissionTemplateEdit Permission = "template_edit"
PermissionTemplateDelete Permission = "template_delete"
PermissionTemplateAccess Permission = "template_access"
)
const (
/*
----- GITSPACE -----
*/
PermissionGitspaceView Permission = "gitspace_view"
PermissionGitspaceCreate Permission = "gitspace_create"
PermissionGitspaceEdit Permission = "gitspace_edit"
PermissionGitspaceDelete Permission = "gitspace_delete"
PermissionGitspaceUse Permission = "gitspace_use"
)
const (
/*
----- INFRAPROVIDER -----
*/
PermissionInfraProviderView Permission = "infraprovider_view"
PermissionInfraProviderEdit Permission = "infraprovider_edit"
PermissionInfraProviderDelete Permission = "infraprovider_delete"
)
const (
/*
----- ARTIFACTS -----
*/
PermissionArtifactsDownload Permission = "artifacts_download"
PermissionArtifactsUpload Permission = "artifacts_upload"
PermissionArtifactsDelete Permission = "artifacts_delete"
PermissionArtifactsQuarantine Permission = "artifacts_quarantine"
)
const (
/*
----- REGISTRY -----
*/
PermissionRegistryView Permission = "registry_view"
PermissionRegistryEdit Permission = "registry_edit"
PermissionRegistryDelete Permission = "registry_delete"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/communication_protocol.go | types/enum/communication_protocol.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type CommunicationProtocol string
func (CommunicationProtocol) Enum() []any { return toInterfaceSlice(communicationProtocols) }
var communicationProtocols = []CommunicationProtocol{
CommunicationProtocolHTTP, CommunicationProtocolSSH,
}
const (
CommunicationProtocolHTTP CommunicationProtocol = "http"
CommunicationProtocolSSH CommunicationProtocol = "ssh"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/principal.go | types/enum/principal.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// PrincipalType defines the supported types of principals.
type PrincipalType string
func (PrincipalType) Enum() []any { return toInterfaceSlice(principalTypes) }
func (s PrincipalType) Sanitize() (PrincipalType, bool) { return Sanitize(s, GetAllPrincipalTypes) }
func GetAllPrincipalTypes() ([]PrincipalType, PrincipalType) { return principalTypes, "" }
const (
// PrincipalTypeUser represents a user.
PrincipalTypeUser PrincipalType = "user"
// PrincipalTypeServiceAccount represents a service account.
PrincipalTypeServiceAccount PrincipalType = "serviceaccount"
// PrincipalTypeService represents a service.
PrincipalTypeService PrincipalType = "service"
)
var principalTypes = sortEnum([]PrincipalType{
PrincipalTypeUser,
PrincipalTypeServiceAccount,
PrincipalTypeService,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/gitspace_state_type.go | types/enum/gitspace_state_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type GitspaceStateType string
func (GitspaceStateType) Enum() []any {
return toInterfaceSlice(gitspaceStateTypes)
}
var gitspaceStateTypes = []GitspaceStateType{
GitspaceStateRunning,
GitspaceStateStopped,
GitspaceStateError,
GitspaceStateUninitialized,
GitspaceStateStarting,
GitspaceStateStopping,
GitSpaceStateCleaning,
}
const (
GitspaceStateRunning GitspaceStateType = "running"
GitspaceStateStopped GitspaceStateType = "stopped"
GitspaceStateStarting GitspaceStateType = "starting"
GitspaceStateStopping GitspaceStateType = "stopping"
GitSpaceStateCleaning GitspaceStateType = "cleaning"
GitspaceStateError GitspaceStateType = "error"
GitspaceStateUninitialized GitspaceStateType = "uninitialized"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/resolver_kind.go | types/enum/resolver_kind.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "fmt"
// ResolverKind represents the kind of resolver.
type ResolverKind string
const (
// ResolverKindPlugin is a plugin resolver.
ResolverKindPlugin ResolverKind = "plugin"
// ResolverKindTemplate is a template resolver.
ResolverKindTemplate ResolverKind = "template"
)
func ParseResolverKind(r string) (ResolverKind, error) {
switch r {
case "plugin":
return ResolverKindPlugin, nil
case "template":
return ResolverKindTemplate, nil
default:
return "", fmt.Errorf("unknown resolver kind provided: %s", r)
}
}
func (r ResolverKind) String() string {
switch r {
case ResolverKindPlugin:
return "plugin"
case ResolverKindTemplate:
return "template"
default:
return undefined
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/common.go | types/enum/common.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"golang.org/x/exp/constraints"
"golang.org/x/exp/slices"
)
func Sanitize[E constraints.Ordered](element E, all func() ([]E, E)) (E, bool) {
allValues, defValue := all()
var empty E
if element == empty && defValue != empty {
return defValue, true
}
idx, exists := slices.BinarySearch(allValues, element)
if exists {
return allValues[idx], true
}
return defValue, false
}
const (
id = "id"
// TODO [CODE-1363]: remove after identifier migration.
uid = "uid"
identifier = "identifier"
name = "name"
email = "email"
admin = "admin"
created = "created"
createdAt = "created_at"
updated = "updated"
updatedAt = "updated_at"
deleted = "deleted"
deletedAt = "deleted_at"
displayName = "display_name"
date = "date"
defaultString = "default"
undefined = "undefined"
system = "system"
asc = "asc"
ascending = "ascending"
desc = "desc"
descending = "descending"
value = "value"
lastUsed = "last_used"
lastActivated = "last_activated"
lastGITPush = "last_git_push"
)
func toInterfaceSlice[T any](vals []T) []any {
res := make([]any, len(vals))
for i := range vals {
res[i] = vals[i]
}
return res
}
func sortEnum[T constraints.Ordered](slice []T) []T {
slices.Sort(slice)
return slice
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/user_test.go | types/enum/user_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "testing"
func TestParseUserAttr(t *testing.T) {
tests := []struct {
text string
want UserAttr
}{
{"uid", UserAttrUID},
{"name", UserAttrName},
{"email", UserAttrEmail},
{"created", UserAttrCreated},
{"updated", UserAttrUpdated},
{"admin", UserAttrAdmin},
{"", UserAttrNone},
{"invalid", UserAttrNone},
}
for _, test := range tests {
got, want := ParseUserAttr(test.text), test.want
if got != want {
t.Errorf("Want user attribute %q parsed as %q, got %q", test.text, want, got)
}
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/label.go | types/enum/label.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type LabelType string
func (LabelType) Enum() []any { return toInterfaceSlice(LabelTypes) }
func (t LabelType) Sanitize() (LabelType, bool) { return Sanitize(t, GetAllLabelTypes) }
func GetAllLabelTypes() ([]LabelType, LabelType) { return LabelTypes, LabelTypeStatic }
const (
LabelTypeStatic LabelType = "static"
LabelTypeDynamic LabelType = "dynamic"
)
var LabelTypes = sortEnum([]LabelType{
LabelTypeStatic,
LabelTypeDynamic,
})
type LabelColor string
func (LabelColor) Enum() []any { return toInterfaceSlice(LabelColors) }
func (t LabelColor) Sanitize() (LabelColor, bool) { return Sanitize(t, GetAllLabelColors) }
func GetAllLabelColors() ([]LabelColor, LabelColor) { return LabelColors, LabelColorBlue }
const (
LabelColorRed LabelColor = "red"
LabelColorGreen LabelColor = "green"
LabelColorYellow LabelColor = "yellow"
LabelColorBlue LabelColor = "blue"
LabelColorPink LabelColor = "pink"
LabelColorPurple LabelColor = "purple"
LabelColorViolet LabelColor = "violet"
LabelColorIndigo LabelColor = "indigo"
LabelColorCyan LabelColor = "cyan"
LabelColorOrange LabelColor = "orange"
LabelColorBrown LabelColor = "brown"
LabelColorMint LabelColor = "mint"
LabelColorLime LabelColor = "lime"
)
var LabelColors = sortEnum([]LabelColor{
LabelColorRed,
LabelColorGreen,
LabelColorYellow,
LabelColorBlue,
LabelColorPink,
LabelColorPurple,
LabelColorViolet,
LabelColorIndigo,
LabelColorCyan,
LabelColorOrange,
LabelColorBrown,
LabelColorMint,
LabelColorLime,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/gitspace_action_type.go | types/enum/gitspace_action_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type GitspaceActionType string
func (GitspaceActionType) Enum() []any { return toInterfaceSlice(gitspaceActionTypes) }
var gitspaceActionTypes = []GitspaceActionType{
GitspaceActionTypeStart, GitspaceActionTypeStop, GitspaceActionTypeReset,
}
const (
GitspaceActionTypeStart GitspaceActionType = "start"
GitspaceActionTypeStop GitspaceActionType = "stop"
GitspaceActionTypeReset GitspaceActionType = "reset"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/events/wire.go | events/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package events
import (
"errors"
"fmt"
"github.com/harness/gitness/stream"
"github.com/go-redis/redis/v8"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideSystem,
)
func ProvideSystem(config Config, redisClient redis.UniversalClient) (*System, error) {
if err := config.Validate(); err != nil {
return nil, fmt.Errorf("provided config is invalid: %w", err)
}
var system *System
var err error
switch config.Mode {
case ModeInMemory:
system, err = provideSystemInMemory(config)
case ModeRedis:
system, err = provideSystemRedis(config, redisClient)
default:
return nil, fmt.Errorf("events system mode '%s' is not supported", config.Mode)
}
if err != nil {
return nil, fmt.Errorf("failed to setup event system for mode '%s': %w", config.Mode, err)
}
return system, nil
}
func provideSystemInMemory(config Config) (*System, error) {
broker, err := stream.NewMemoryBroker(config.MaxStreamLength)
if err != nil {
return nil, err
}
return NewSystem(
newMemoryStreamConsumerFactoryMethod(broker, config.Namespace),
newMemoryStreamProducer(broker, config.Namespace),
)
}
func provideSystemRedis(config Config, redisClient redis.UniversalClient) (*System, error) {
if redisClient == nil {
return nil, errors.New("redis client required")
}
return NewSystem(
newRedisStreamConsumerFactoryMethod(redisClient, config.Namespace),
newRedisStreamProducer(redisClient, config.Namespace,
config.MaxStreamLength, config.ApproxMaxStreamLength),
)
}
func newMemoryStreamConsumerFactoryMethod(broker *stream.MemoryBroker, namespace string) StreamConsumerFactoryFunc {
return func(groupName string, _ string) (StreamConsumer, error) {
return stream.NewMemoryConsumer(broker, namespace, groupName)
}
}
func newMemoryStreamProducer(broker *stream.MemoryBroker, namespace string) StreamProducer {
return stream.NewMemoryProducer(broker, namespace)
}
func newRedisStreamConsumerFactoryMethod(
redisClient redis.UniversalClient,
namespace string,
) StreamConsumerFactoryFunc {
return func(groupName string, consumerName string) (StreamConsumer, error) {
return stream.NewRedisConsumer(redisClient, namespace, groupName, consumerName)
}
}
func newRedisStreamProducer(redisClient redis.UniversalClient, namespace string,
maxStreamLength int64, approxMaxStreamLength bool) StreamProducer {
return stream.NewRedisProducer(redisClient, namespace, maxStreamLength, approxMaxStreamLength)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/events/stream.go | events/stream.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package events
import (
"context"
"github.com/harness/gitness/stream"
)
// StreamProducer is an abstraction of a producer from the streams package.
type StreamProducer interface {
Send(ctx context.Context, streamID string, payload map[string]any) (string, error)
}
// StreamConsumer is an abstraction of a consumer from the streams package.
type StreamConsumer interface {
Register(streamID string, handler stream.HandlerFunc, opts ...stream.HandlerOption) error
Configure(opts ...stream.ConsumerOption)
Start(ctx context.Context) error
Errors() <-chan error
Infos() <-chan string
}
// StreamConsumerFactoryFunc is an abstraction of a factory method for stream consumers.
type StreamConsumerFactoryFunc func(groupName string, consumerName string) (StreamConsumer, error)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/events/error.go | events/error.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package events
import (
"errors"
"fmt"
)
var (
errDiscardEvent = &discardEventError{}
)
// discardEventError is an error which, if returned by the event handler,
// causes the source event to be discarded despite any errors.
type discardEventError struct {
inner error
}
func NewDiscardEventError(inner error) error {
return &discardEventError{
inner: inner,
}
}
func NewDiscardEventErrorf(format string, args ...any) error {
return &discardEventError{
inner: fmt.Errorf(format, args...),
}
}
func (e *discardEventError) Error() string {
return fmt.Sprintf("discarding requested due to: %s", e.inner)
}
func (e *discardEventError) Unwrap() error {
return e.inner
}
func (e *discardEventError) Is(target error) bool {
// NOTE: it's an internal event and we only ever check with the singleton instance
return errors.Is(target, errDiscardEvent)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/events/reader.go | events/reader.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package events
import (
"bytes"
"context"
"encoding/gob"
"errors"
"fmt"
"github.com/rs/zerolog/log"
)
// ReaderFactoryFunc is an abstraction of a factory method that creates customized Reader implementations (type [R]).
// It is triggered by the ReaderFactory to create a new instance of the Reader to launch.
// The provided GenericReader object is available exclusively to the factory method (every call has a fresh instance)
// and should be used as base of any custom Reader implementation (use ReaderRegisterEvent to register custom handler).
type ReaderFactoryFunc[R Reader] func(reader *GenericReader) (R, error)
// ReaderFactory allows to launch event readers of type [R] (can be GenericReader or customized readers).
type ReaderFactory[R Reader] struct {
category string
streamConsumerFactoryFn StreamConsumerFactoryFunc
readerFactoryFn ReaderFactoryFunc[R]
}
// Launch launches a new reader for the provided group and client name.
// The setup method should be used to register the different events the reader will act on.
// To stop the reader and cleanup its resources the returned ReaderCanceler can be used.
// The reader also cancels automatically when the provided context is canceled.
// NOTE: Do not setup the reader outside of the setup method!
func (f *ReaderFactory[R]) Launch(ctx context.Context,
groupName string, readerName string, setup func(R) error) (*ReaderCanceler, error) {
if groupName == "" {
return nil, errors.New("groupName can't be empty")
}
if setup == nil {
return nil, errors.New("setup function can't be nil")
}
// setup ctx with copied logger that has extra fields set
log := log.Ctx(ctx).With().
Str("events.category", f.category).
Str("events.group_name", groupName).
Str("events.reader_name", readerName).
Logger()
// create new stream consumer using factory method
streamConsumer, err := f.streamConsumerFactoryFn(groupName, readerName)
if err != nil {
return nil, fmt.Errorf("failed to create new stream consumer: %w", err)
}
// create generic reader object
innerReader := &GenericReader{
streamConsumer: streamConsumer,
category: f.category,
}
// create new reader (could return the innerReader itself, but also allows to launch customized readers)
reader, err := f.readerFactoryFn(innerReader)
if err != nil {
//nolint:gocritic // only way to achieve this AFAIK - lint proposal is not building
return nil, fmt.Errorf("failed creation of event reader of type %T: %w", *new(R), err)
}
// execute setup function on reader (will configure concurrency, processingTimeout, ..., and register handlers)
err = setup(reader)
if err != nil {
return nil, fmt.Errorf("failed custom setup of event reader: %w", err)
}
// hook into all available logs
go func(errorCh <-chan error) {
for err := range errorCh {
log.Err(err).Msg("received an error from stream consumer")
}
}(streamConsumer.Errors())
go func(infoCh <-chan string) {
for s := range infoCh {
log.Info().Msgf("stream consumer: %s", s)
}
}(streamConsumer.Infos())
// prepare context (inject logger and make canceable)
ctx = log.WithContext(ctx)
ctx, cancelFn := context.WithCancel(ctx)
// start consumer
err = innerReader.streamConsumer.Start(ctx)
if err != nil {
cancelFn()
return nil, fmt.Errorf("failed to start consumer: %w", err)
}
return &ReaderCanceler{
cancelFn: func() error {
cancelFn()
return nil
},
}, nil
}
// ReaderCanceler exposes the functionality to cancel a reader explicitly.
type ReaderCanceler struct {
canceled bool
cancelFn func() error
}
func (d *ReaderCanceler) Cancel() error {
if d.canceled {
return errors.New("reader has already been canceled")
}
// call cancel (might be async)
err := d.cancelFn()
if err != nil {
return fmt.Errorf("failed to cancel reader: %w", err)
}
d.canceled = true
return nil
}
// Reader specifies the minimum functionality a reader should expose.
// NOTE: we don't want to enforce any event registration methods here, allowing full control for customized readers.
type Reader interface {
Configure(opts ...ReaderOption)
}
type HandlerFunc[T any] func(context.Context, *Event[T]) error
// GenericReader represents an event reader that supports registering type safe handlers
// for an arbitrary set of custom events within a given event category using the ReaderRegisterEvent method.
// NOTE: Optimally this should be an interface with RegisterEvent[T] method, but that's currently not possible in go.
// IMPORTANT: This reader should not be instantiated from external packages.
type GenericReader struct {
streamConsumer StreamConsumer
category string
}
// ReaderRegisterEvent registers a type safe handler function on the reader for a specific event.
// This method allows to register type safe handlers without the need of handling the raw stream payload.
// NOTE: Generic arguments are not allowed for struct methods, hence pass the reader as input parameter.
func ReaderRegisterEvent[T any](reader *GenericReader,
eventType EventType, fn HandlerFunc[T], opts ...HandlerOption) error {
streamID := getStreamID(reader.category, eventType)
// register handler for event specific stream.
return reader.streamConsumer.Register(streamID,
func(ctx context.Context, messageID string, streamPayload map[string]any) error {
if streamPayload == nil {
return fmt.Errorf("stream payload is nil for message '%s'", messageID)
}
// retrieve event from stream payload
eventRaw, ok := streamPayload[streamPayloadKey]
if !ok {
return fmt.Errorf("stream payload doesn't contain event (key: '%s') for message '%s'", streamPayloadKey, messageID)
}
// retrieve bytes from raw event
// NOTE: Redis returns []byte as string - to avoid unnecessary conversion we handle both types here.
var eventBytes []byte
switch v := eventRaw.(type) {
case string:
eventBytes = []byte(v)
case []byte:
eventBytes = v
default:
return fmt.Errorf("stream payload is not of expected type string or []byte but of type %T (message '%s')",
eventRaw, messageID)
}
// decode event to correct type
var event Event[T]
decoder := gob.NewDecoder(bytes.NewReader(eventBytes))
err := decoder.Decode(&event)
if err != nil {
//nolint:gocritic // only way to achieve this AFAIK - lint proposal is not building
return fmt.Errorf("stream payload can't be decoded into type %T (message '%s')", *new(T), messageID)
}
// populate event ID using the message ID (has to be populated here, producer doesn't know the message ID yet)
event.ID = messageID
// update ctx with event type for proper logging
log := log.Ctx(ctx).With().
Str("events.type", string(eventType)).
Str("events.id", event.ID).
Logger()
ctx = log.WithContext(ctx)
// call provided handler with correctly typed payload
err = fn(ctx, &event)
// handle discardEventError
if errors.Is(err, errDiscardEvent) {
log.Warn().Err(err).Msgf("discarding event '%s'", event.ID)
return nil
}
// any other error we return as is
return err
}, toStreamHandlerOptions(opts)...)
}
func (r *GenericReader) Configure(opts ...ReaderOption) {
r.streamConsumer.Configure(toStreamConsumerOptions(opts)...)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/events/reporter.go | events/reporter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package events
import (
"bytes"
"context"
"encoding/gob"
"fmt"
"time"
"github.com/harness/gitness/app/gitspace/orchestrator/container/response"
)
// GenericReporter represents an event reporter that supports sending typesafe messages
// for an arbitrary set of custom events within an event category using the ReporterSendEvent method.
// NOTE: Optimally this should be an interface with SendEvent[T] method, but that's not possible in go.
type GenericReporter struct {
producer StreamProducer
category string
}
// ReportEvent reports an event using the provided GenericReporter.
// Returns the reported event's ID in case of success.
// NOTE: This call is blocking until the event was send (not until it was processed).
//
//nolint:revive // emphasize that this is meant to be an operation on *GenericReporter
func ReporterSendEvent[T any](reporter *GenericReporter, ctx context.Context,
eventType EventType, payload T) (string, error) {
streamID := getStreamID(reporter.category, eventType)
event := Event[T]{
ID: "", // will be set by GenericReader
Timestamp: time.Now(),
Payload: payload,
}
buff := &bytes.Buffer{}
encoder := gob.NewEncoder(buff)
gob.Register((*response.StartResponse)(nil))
gob.Register((*response.StopResponse)(nil))
gob.Register((*response.DeleteResponse)(nil))
if err := encoder.Encode(&event); err != nil {
return "", fmt.Errorf("failed to encode payload: %w", err)
}
streamPayload := map[string]any{
streamPayloadKey: buff.Bytes(),
}
// We are using the message ID as event ID.
return reporter.producer.Send(ctx, streamID, streamPayload)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/events/system.go | events/system.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package events
import "errors"
// System represents a single contained event system that is used
// to setup event Reporters and ReaderFactories.
type System struct {
streamConsumerFactoryFn StreamConsumerFactoryFunc
streamProducer StreamProducer
}
func NewSystem(streamConsumerFactoryFunc StreamConsumerFactoryFunc, streamProducer StreamProducer) (*System, error) {
if streamConsumerFactoryFunc == nil {
return nil, errors.New("streamConsumerFactoryFunc can't be empty")
}
if streamProducer == nil {
return nil, errors.New("streamProducer can't be empty")
}
return &System{
streamConsumerFactoryFn: streamConsumerFactoryFunc,
streamProducer: streamProducer,
}, nil
}
func NewReaderFactory[R Reader](system *System, category string, fn ReaderFactoryFunc[R]) (*ReaderFactory[R], error) {
if system == nil {
return nil, errors.New("system can't be empty")
}
if category == "" {
return nil, errors.New("category can't be empty")
}
if fn == nil {
return nil, errors.New("fn can't be empty")
}
return &ReaderFactory[R]{
// values coming from system
streamConsumerFactoryFn: system.streamConsumerFactoryFn,
// values coming from input parameters
category: category,
readerFactoryFn: fn,
}, nil
}
func NewReporter(system *System, category string) (*GenericReporter, error) {
if system == nil {
return nil, errors.New("system can't be empty")
}
if category == "" {
return nil, errors.New("category can't be empty")
}
return &GenericReporter{
// values coming from system
producer: system.streamProducer,
// values coming from input parameters
category: category,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/events/options.go | events/options.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package events
import (
"time"
"github.com/harness/gitness/stream"
)
/*
* Expose event package options to simplify usage for consumers by hiding the stream package.
* Since we only forward the options, event options are simply aliases of stream options.
*/
// ReaderOption can be used to configure event readers.
type ReaderOption stream.ConsumerOption
func toStreamConsumerOptions(opts []ReaderOption) []stream.ConsumerOption {
streamOpts := make([]stream.ConsumerOption, len(opts))
for i, opt := range opts {
streamOpts[i] = stream.ConsumerOption(opt)
}
return streamOpts
}
// WithConcurrency sets up the concurrency of the reader.
func WithConcurrency(concurrency int) ReaderOption {
return stream.WithConcurrency(concurrency)
}
// WithHandlerOptions sets up the default options for event handlers.
func WithHandlerOptions(opts ...HandlerOption) ReaderOption {
return stream.WithHandlerOptions(toStreamHandlerOptions(opts)...)
}
// HandlerOption can be used to configure event handlers.
type HandlerOption stream.HandlerOption
func toStreamHandlerOptions(opts []HandlerOption) []stream.HandlerOption {
streamOpts := make([]stream.HandlerOption, len(opts))
for i, opt := range opts {
streamOpts[i] = stream.HandlerOption(opt)
}
return streamOpts
}
// WithMaxRetries can be used to set the max retry count for a specific event handler.
func WithMaxRetries(maxRetries int) HandlerOption {
return stream.WithMaxRetries(maxRetries)
}
// WithIdleTimeout can be used to set the idle timeout for a specific event handler.
func WithIdleTimeout(timeout time.Duration) HandlerOption {
return stream.WithIdleTimeout(timeout)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/events/events.go | events/events.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package events
import (
"errors"
"fmt"
"time"
)
const (
// streamPayloadKey is the key used for storing the event in a stream message.
streamPayloadKey = "event"
)
type Event[T any] struct {
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
Payload T `json:"payload"`
}
// EventType describes the type of event.
type EventType string
// getStreamID generates the streamID for a given category and type of event.
func getStreamID(category string, event EventType) string {
return fmt.Sprintf("events:%s:%s", category, event)
}
// Mode defines the different modes of the event framework.
type Mode string
const (
ModeRedis Mode = "redis"
ModeInMemory Mode = "inmemory"
)
// Config defines the config of the events system.
type Config struct {
Mode Mode
Namespace string
MaxStreamLength int64
ApproxMaxStreamLength bool
}
func (c *Config) Validate() error {
if c == nil {
return errors.New("config is required")
}
if c.Mode != ModeRedis && c.Mode != ModeInMemory {
return fmt.Errorf("config.Mode '%s' is not supported", c.Mode)
}
if c.MaxStreamLength < 1 {
return errors.New("config.MaxStreamLength has to be a positive number")
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/audit/wire.go | audit/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package audit
import "github.com/google/wire"
var WireSet = wire.NewSet(
ProvideAuditService,
)
func ProvideAuditService() Service {
return New()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/audit/middleware.go | audit/middleware.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package audit
import (
"context"
"net"
"net/http"
"strings"
)
var (
trueClientIP = http.CanonicalHeaderKey("True-Client-IP")
xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
xRealIP = http.CanonicalHeaderKey("X-Real-IP")
)
// Middleware process request headers to fill internal info data.
func Middleware() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if rip := RealIP(r); rip != "" {
ctx = context.WithValue(ctx, realIPKey, rip)
}
ctx = context.WithValue(ctx, pathKey, r.URL.Path)
ctx = context.WithValue(ctx, requestMethod, r.Method)
ctx = context.WithValue(ctx, requestID, w.Header().Get("X-Request-Id"))
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
}
// RealIP extracts the real client IP from the HTTP request.
func RealIP(r *http.Request) string {
var ip string
if tcip := r.Header.Get(trueClientIP); tcip != "" {
ip = tcip
} else if xrip := r.Header.Get(xRealIP); xrip != "" {
ip = xrip
} else if xff := r.Header.Get(xForwardedFor); xff != "" {
i := strings.Index(xff, ",")
if i == -1 {
i = len(xff)
}
ip = xff[:i]
} else {
ip = strings.Split(r.RemoteAddr, ":")[0]
}
if ip == "" || net.ParseIP(ip) == nil {
return ""
}
return ip
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/audit/context_test.go | audit/context_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package audit
import (
"context"
"testing"
)
func TestGetRealIP(t *testing.T) {
t.Run("returns IP when present", func(t *testing.T) {
ctx := context.WithValue(context.Background(), realIPKey, "192.168.1.1")
ip := GetRealIP(ctx)
if ip != "192.168.1.1" {
t.Errorf("expected IP to be '192.168.1.1', got '%s'", ip)
}
})
t.Run("returns empty string when not present", func(t *testing.T) {
ctx := context.Background()
ip := GetRealIP(ctx)
if ip != "" {
t.Errorf("expected empty string, got '%s'", ip)
}
})
t.Run("returns empty string when wrong type", func(t *testing.T) {
ctx := context.WithValue(context.Background(), realIPKey, 12345)
ip := GetRealIP(ctx)
if ip != "" {
t.Errorf("expected empty string, got '%s'", ip)
}
})
t.Run("handles IPv6 address", func(t *testing.T) {
ctx := context.WithValue(context.Background(), realIPKey, "2001:0db8:85a3:0000:0000:8a2e:0370:7334")
ip := GetRealIP(ctx)
if ip != "2001:0db8:85a3:0000:0000:8a2e:0370:7334" {
t.Errorf("expected IPv6 address, got '%s'", ip)
}
})
}
func TestGetPath(t *testing.T) {
t.Run("returns path when present", func(t *testing.T) {
ctx := context.WithValue(context.Background(), pathKey, "/api/v1/users")
path := GetPath(ctx)
if path != "/api/v1/users" {
t.Errorf("expected path to be '/api/v1/users', got '%s'", path)
}
})
t.Run("returns empty string when not present", func(t *testing.T) {
ctx := context.Background()
path := GetPath(ctx)
if path != "" {
t.Errorf("expected empty string, got '%s'", path)
}
})
t.Run("returns empty string when wrong type", func(t *testing.T) {
ctx := context.WithValue(context.Background(), pathKey, 12345)
path := GetPath(ctx)
if path != "" {
t.Errorf("expected empty string, got '%s'", path)
}
})
t.Run("handles empty path", func(t *testing.T) {
ctx := context.WithValue(context.Background(), pathKey, "")
path := GetPath(ctx)
if path != "" {
t.Errorf("expected empty string, got '%s'", path)
}
})
}
func TestGetRequestID(t *testing.T) {
t.Run("returns request ID when present", func(t *testing.T) {
ctx := context.WithValue(context.Background(), requestID, "req-12345")
id := GetRequestID(ctx)
if id != "req-12345" {
t.Errorf("expected request ID to be 'req-12345', got '%s'", id)
}
})
t.Run("returns empty string when not present", func(t *testing.T) {
ctx := context.Background()
id := GetRequestID(ctx)
if id != "" {
t.Errorf("expected empty string, got '%s'", id)
}
})
t.Run("returns empty string when wrong type", func(t *testing.T) {
ctx := context.WithValue(context.Background(), requestID, 12345)
id := GetRequestID(ctx)
if id != "" {
t.Errorf("expected empty string, got '%s'", id)
}
})
t.Run("handles UUID format", func(t *testing.T) {
uuid := "550e8400-e29b-41d4-a716-446655440000"
ctx := context.WithValue(context.Background(), requestID, uuid)
id := GetRequestID(ctx)
if id != uuid {
t.Errorf("expected request ID to be '%s', got '%s'", uuid, id)
}
})
}
func TestGetRequestMethod(t *testing.T) {
t.Run("returns method when present", func(t *testing.T) {
ctx := context.WithValue(context.Background(), requestMethod, "GET")
method := GetRequestMethod(ctx)
if method != "GET" {
t.Errorf("expected method to be 'GET', got '%s'", method)
}
})
t.Run("returns empty string when not present", func(t *testing.T) {
ctx := context.Background()
method := GetRequestMethod(ctx)
if method != "" {
t.Errorf("expected empty string, got '%s'", method)
}
})
t.Run("returns empty string when wrong type", func(t *testing.T) {
ctx := context.WithValue(context.Background(), requestMethod, 12345)
method := GetRequestMethod(ctx)
if method != "" {
t.Errorf("expected empty string, got '%s'", method)
}
})
t.Run("handles various HTTP methods", func(t *testing.T) {
methods := []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"}
for _, m := range methods {
ctx := context.WithValue(context.Background(), requestMethod, m)
method := GetRequestMethod(ctx)
if method != m {
t.Errorf("expected method to be '%s', got '%s'", m, method)
}
}
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/audit/interface.go | audit/interface.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package audit
import (
"context"
"github.com/harness/gitness/types"
)
type Service interface {
Log(
ctx context.Context,
user types.Principal,
resource Resource,
action Action,
spacePath string,
options ...Option,
) error
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/audit/audit.go | audit/audit.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package audit
import (
"context"
"errors"
"fmt"
"github.com/harness/gitness/types"
)
var (
ErrActionUndefined = errors.New("undefined action")
ErrResourceTypeUndefined = errors.New("undefined resource type")
ErrResourceIdentifierIsRequired = errors.New("resource identifier is required")
ErrUserIsRequired = errors.New("user is required")
ErrSpacePathIsRequired = errors.New("space path is required")
)
const (
ResourceName = "resourceName"
RepoName = "repoName"
SpaceName = "spaceName"
RegistryName = "registryName"
BypassedResourceType = "bypassedResourceType"
BypassedResourceName = "bypassedResourceName"
RepoPath = "repoPath"
BypassedResourceTypePullRequest = "pull_request"
BypassedResourceTypeBranch = "branch"
BypassedResourceTypeTag = "tag"
BypassedResourceTypeCommit = "commit"
BypassAction = "bypass_action"
BypassActionDeleted = "deleted"
BypassActionCreated = "created"
BypassActionCommitted = "committed"
BypassActionMerged = "merged"
BypassSHALabelFormat = "%s @%s"
BypassPullReqLabelFormat = "%s #%s"
)
type Action string
const (
ActionCreated Action = "created"
ActionUpdated Action = "updated" // update default branch, switching default branch, updating description
ActionDeleted Action = "deleted"
ActionBypassed Action = "bypassed"
ActionForcePush Action = "forcePush"
)
func (a Action) Validate() error {
switch a {
case ActionCreated, ActionUpdated, ActionDeleted, ActionBypassed, ActionForcePush:
return nil
default:
return ErrActionUndefined
}
}
type ResourceType string
const (
ResourceTypeRepository ResourceType = "repository"
ResourceTypeBranchRule ResourceType = "branch_rule"
ResourceTypeBranch ResourceType = "branch"
ResourceTypeTag ResourceType = "tag"
ResourceTypeTagRule ResourceType = "tag_rule"
ResourceTypePushRule ResourceType = "push_rule"
ResourceTypePullRequest ResourceType = "pull_request"
ResourceTypeRepositorySettings ResourceType = "repository_settings"
ResourceTypeCodeWebhook ResourceType = "code_webhook"
ResourceTypeRegistry ResourceType = "registry"
ResourceTypeRegistryUpstreamProxy ResourceType = "registry_upstream_proxy"
ResourceTypeRegistryWebhook ResourceType = "registry_webhook"
ResourceTypeRegistryArtifact ResourceType = "registry_artifact"
)
func (a ResourceType) Validate() error {
switch a {
case ResourceTypeRepository,
ResourceTypeBranchRule,
ResourceTypeBranch,
ResourceTypeTag,
ResourceTypeTagRule,
ResourceTypePushRule,
ResourceTypePullRequest,
ResourceTypeRepositorySettings,
ResourceTypeCodeWebhook,
ResourceTypeRegistry,
ResourceTypeRegistryUpstreamProxy,
ResourceTypeRegistryWebhook,
ResourceTypeRegistryArtifact:
return nil
default:
return ErrResourceTypeUndefined
}
}
type Resource struct {
Type ResourceType
Identifier string
Data map[string]string
}
func NewResource(rtype ResourceType, identifier string, keyValues ...string) Resource {
r := Resource{
Type: rtype,
Identifier: identifier,
Data: make(map[string]string, len(keyValues)),
}
for i := 0; i < len(keyValues); i += 2 {
k, v := keyValues[i], keyValues[i+1]
r.Data[k] = v
}
return r
}
func (r Resource) Validate() error {
if err := r.Type.Validate(); err != nil {
return err
}
if r.Identifier == "" {
return ErrResourceIdentifierIsRequired
}
return nil
}
func (r Resource) DataAsSlice() []string {
slice := make([]string, 0, len(r.Data)*2)
for k, v := range r.Data {
slice = append(slice, k, v)
}
return slice
}
type DiffObject struct {
OldObject any
NewObject any
}
type Event struct {
ID string
Timestamp int64
Action Action // example: ActionCreated
User types.Principal // example: Admin
SpacePath string // example: /root/projects
Resource Resource
DiffObject DiffObject
ClientIP string
RequestMethod string
Data map[string]string // internal data like correlationID/requestID
}
func (e *Event) Validate() error {
if err := e.Action.Validate(); err != nil {
return fmt.Errorf("invalid action: %w", err)
}
if e.User.UID == "" {
return ErrUserIsRequired
}
if e.SpacePath == "" {
return ErrSpacePathIsRequired
}
if err := e.Resource.Validate(); err != nil {
return fmt.Errorf("invalid resource: %w", err)
}
return nil
}
type Noop struct{}
func New() *Noop {
return &Noop{}
}
func (s *Noop) Log(
context.Context,
types.Principal,
Resource,
Action,
string,
...Option,
) error {
// No implementation
return nil
}
type FuncOption func(e *Event)
func (f FuncOption) Apply(event *Event) {
f(event)
}
type Option interface {
Apply(e *Event)
}
func WithID(value string) FuncOption {
return func(e *Event) {
e.ID = value
}
}
func WithNewObject(value any) FuncOption {
return func(e *Event) {
e.DiffObject.NewObject = value
}
}
func WithOldObject(value any) FuncOption {
return func(e *Event) {
e.DiffObject.OldObject = value
}
}
func WithClientIP(value string) FuncOption {
return func(e *Event) {
e.ClientIP = value
}
}
func WithRequestMethod(value string) FuncOption {
return func(e *Event) {
e.RequestMethod = value
}
}
func WithData(keyValues ...string) FuncOption {
return func(e *Event) {
if e.Data == nil {
e.Data = make(map[string]string)
}
for i := 0; i < len(keyValues); i += 2 {
k, v := keyValues[i], keyValues[i+1]
e.Data[k] = v
}
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/audit/objects.go | audit/objects.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package audit
import (
"time"
registrytypes "github.com/harness/gitness/registry/types"
"github.com/harness/gitness/types"
)
// RepositoryObject is the object used for emitting repository related audits.
// TODO: ensure audit only takes audit related objects?
type RepositoryObject struct {
types.Repository
IsPublic bool `yaml:"is_public"`
}
type RegistryObject struct {
registrytypes.Registry
}
type PullRequestObject struct {
PullReq types.PullReq
RepoPath string `yaml:"repo_path"`
RuleViolations []types.RuleViolations `yaml:"rule_violations"`
}
type CommitObject struct {
CommitSHA string `yaml:"commit_sha"`
RepoPath string `yaml:"repo_path"`
RuleViolations []types.RuleViolations `yaml:"rule_violations"`
}
type CommitTagObject struct {
TagName string `yaml:"tag_name"`
RepoPath string `yaml:"repo_path"`
RuleViolations []types.RuleViolations `yaml:"rule_violations"`
}
type BranchObject struct {
BranchName string `yaml:"branch_name"`
RepoPath string `yaml:"repo_path"`
RuleViolations []types.RuleViolations `yaml:"rule_violations"`
}
type RegistryUpstreamProxyConfigObject struct {
ID int64
RegistryID int64
Source string
URL string
AuthType string
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/audit/context.go | audit/context.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package audit
import "context"
type key int
const (
realIPKey key = iota
requestID
requestMethod
pathKey
)
// GetRealIP returns IP address from context.
func GetRealIP(ctx context.Context) string {
ip, ok := ctx.Value(realIPKey).(string)
if !ok {
return ""
}
return ip
}
// GetPath returns Path from context.
func GetPath(ctx context.Context) string {
path, ok := ctx.Value(pathKey).(string)
if !ok {
return ""
}
return path
}
// GetRequestID returns requestID from context.
func GetRequestID(ctx context.Context) string {
id, ok := ctx.Value(requestID).(string)
if !ok {
return ""
}
return id
}
// GetRequestMethod returns http method from context.
func GetRequestMethod(ctx context.Context) string {
method, ok := ctx.Value(requestMethod).(string)
if !ok {
return ""
}
return method
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/merge.go | git/merge.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"time"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/enum"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/merge"
"github.com/harness/gitness/git/parser"
"github.com/harness/gitness/git/sha"
"github.com/harness/gitness/git/sharedrepo"
)
// MergeParams is input structure object for merging operation.
type MergeParams struct {
WriteParams
// BaseSHA is the target SHA when we want to merge. Either BaseSHA or BaseBranch must be provided.
BaseSHA sha.SHA
// BaseBranch is the target branch where we want to merge. Either BaseSHA or BaseBranch must be provided.
BaseBranch string
// HeadSHA is the source commit we want to merge onto the base. Either HeadSHA or HeadBranch must be provided.
HeadSHA sha.SHA
// HeadBranch is the source branch we want to merge. Either HeadSHA or HeadBranch must be provided.
HeadBranch string
// HeadBranchExpectedSHA is commit SHA on the HeadBranch. Ignored if HeadSHA is provided instead.
// If HeadBranchExpectedSHA is older than the HeadBranch latest SHA then merge will fail.
HeadBranchExpectedSHA sha.SHA
// Merge is the message of the commit that would be created. Ignored for Rebase and FastForward.
Message string
// Committer overwrites the git committer used for committing the files
// (optional, default: actor)
Committer *Identity
// CommitterDate overwrites the git committer date used for committing the files
// (optional, default: current time on server)
CommitterDate *time.Time
// Author overwrites the git author used for committing the files
// (optional, default: committer)
Author *Identity
// AuthorDate overwrites the git author date used for committing the files
// (optional, default: committer date)
AuthorDate *time.Time
Refs []RefUpdate
Force bool
DeleteHeadBranch bool
Method enum.MergeMethod
}
type RefUpdate struct {
// Name is the full name of the reference.
Name string
// Old is the expected current value of the reference.
// If it's empty, the old value of the reference can be any value.
Old sha.SHA
// New is the desired value for the reference.
// If it's empty, the reference would be set to the resulting commit SHA of the merge.
New sha.SHA
}
func (p *MergeParams) Validate() error {
if err := p.WriteParams.Validate(); err != nil {
return err
}
if p.BaseBranch == "" && p.BaseSHA.IsEmpty() {
return errors.InvalidArgument("either base branch or commit SHA is mandatory")
}
if p.HeadBranch == "" && p.HeadSHA.IsEmpty() {
return errors.InvalidArgument("either head branch or head SHA is mandatory")
}
for _, ref := range p.Refs {
if ref.Name == "" {
return errors.InvalidArgument("ref name has to be provided")
}
}
return nil
}
// MergeOutput is result object from merging and returns
// base, head and commit sha.
type MergeOutput struct {
// BaseSHA is the sha of the latest commit on the base branch that was used for merging.
BaseSHA sha.SHA
// HeadSHA is the sha of the latest commit on the head branch that was used for merging.
HeadSHA sha.SHA
// MergeBaseSHA is the sha of the merge base of the HeadSHA and BaseSHA
MergeBaseSHA sha.SHA
// MergeSHA is the sha of the commit after merging HeadSHA with BaseSHA.
MergeSHA sha.SHA
CommitCount int
ChangedFileCount int
Additions int
Deletions int
ConflictFiles []string
}
// Merge method executes git merge operation. Refs can be sha, branch or tag.
// Based on input params.RefType merge can do checking or final merging of two refs.
// some examples:
//
// params.RefType = Undefined -> discard merge commit (only performs a merge check).
// params.RefType = Raw and params.RefName = refs/pull/1/ref will push to refs/pullreq/1/ref
// params.RefType = RefTypeBranch and params.RefName = "somebranch" -> merge and push to refs/heads/somebranch
// params.RefType = RefTypePullReqHead and params.RefName = "1" -> merge and push to refs/pullreq/1/head
// params.RefType = RefTypePullReqMerge and params.RefName = "1" -> merge and push to refs/pullreq/1/merge
//
// There are cases when you want to block merging and for that you will need to provide
// params.HeadBranchExpectedSHA which will be compared with the latest sha from head branch
// if they are not the same error will be returned.
//
//nolint:gocognit,gocyclo,cyclop
func (s *Service) Merge(ctx context.Context, params *MergeParams) (MergeOutput, error) {
err := params.Validate()
if err != nil {
return MergeOutput{}, fmt.Errorf("params not valid: %w", err)
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
// prepare the merge method function
mergeMethod, ok := params.Method.Sanitize()
if !ok && params.Method != "" {
return MergeOutput{}, errors.InvalidArgumentf("Unsupported merge method: %q", params.Method)
}
var mergeFunc merge.Func
switch mergeMethod {
case enum.MergeMethodMerge:
mergeFunc = merge.Merge
case enum.MergeMethodSquash:
mergeFunc = merge.Squash
case enum.MergeMethodRebase:
mergeFunc = merge.Rebase
case enum.MergeMethodFastForward:
mergeFunc = merge.FastForward
default:
// should not happen, the call to Sanitize above should handle this case.
panic(fmt.Sprintf("unsupported merge method: %q", mergeMethod))
}
// find the commit SHAs
baseCommitSHA := params.BaseSHA
if baseCommitSHA.IsEmpty() {
baseCommitSHA, err = s.git.ResolveRev(ctx, repoPath, api.EnsureBranchPrefix(params.BaseBranch))
if err != nil {
return MergeOutput{}, fmt.Errorf("failed to get base branch commit SHA: %w", err)
}
}
headCommitSHA := params.HeadSHA
if headCommitSHA.IsEmpty() {
headCommitSHA, err = s.git.ResolveRev(ctx, repoPath, api.EnsureBranchPrefix(params.HeadBranch))
if err != nil {
return MergeOutput{}, fmt.Errorf("failed to get head branch commit SHA: %w", err)
}
if !params.HeadBranchExpectedSHA.IsEmpty() && !params.HeadBranchExpectedSHA.Equal(headCommitSHA) {
return MergeOutput{}, errors.PreconditionFailedf(
"head branch '%s' is on SHA '%s' which doesn't match expected SHA '%s'.",
params.HeadBranch,
headCommitSHA,
params.HeadBranchExpectedSHA)
}
}
mergeBaseCommitSHA, _, err := s.git.GetMergeBase(ctx, repoPath, "origin",
baseCommitSHA.String(), headCommitSHA.String(), false)
if err != nil {
return MergeOutput{}, fmt.Errorf("failed to get merge base: %w", err)
}
if headCommitSHA.Equal(mergeBaseCommitSHA) {
return MergeOutput{}, errors.InvalidArgument("head branch doesn't contain any new commits.")
}
// find short stat and number of commits
shortStat, err := s.git.DiffShortStat(
ctx,
repoPath,
baseCommitSHA.String(),
headCommitSHA.String(),
true,
false,
)
if err != nil {
return MergeOutput{}, errors.Internalf(err,
"failed to find short stat between %s and %s", baseCommitSHA, headCommitSHA)
}
commitCount, err := merge.CommitCount(ctx, repoPath, baseCommitSHA.String(), headCommitSHA.String())
if err != nil {
return MergeOutput{}, fmt.Errorf("failed to find commit count for merge check: %w", err)
}
// author and committer
now := time.Now().UTC()
committer := api.Signature{Identity: api.Identity(params.Actor), When: now}
if params.Committer != nil {
committer.Identity = api.Identity(*params.Committer)
}
if params.CommitterDate != nil {
committer.When = *params.CommitterDate
}
author := committer
if params.Author != nil {
author.Identity = api.Identity(*params.Author)
}
if params.AuthorDate != nil {
author.When = *params.AuthorDate
}
// create merge commit and update the references
refUpdater, err := hook.CreateRefUpdater(s.hookClientFactory, params.EnvVars, repoPath)
if err != nil {
return MergeOutput{}, fmt.Errorf("failed to create reference updater: %w", err)
}
var mergeCommitSHA sha.SHA
var conflicts []string
err = sharedrepo.Run(ctx, refUpdater, s.sharedRepoRoot, repoPath, func(s *sharedrepo.SharedRepo) error {
message := parser.CleanUpWhitespace(params.Message)
mergeCommitSHA, conflicts, err = mergeFunc(
ctx,
s,
merge.Params{
Author: &author,
Committer: &committer,
Message: message,
MergeBaseSHA: mergeBaseCommitSHA,
TargetSHA: baseCommitSHA,
SourceSHA: headCommitSHA,
})
if err != nil {
return fmt.Errorf("failed to create merge commit: %w", err)
}
if mergeCommitSHA.IsEmpty() || len(conflicts) > 0 {
return refUpdater.Init(ctx, nil) // update nothing
}
refUpdates := make([]hook.ReferenceUpdate, len(params.Refs))
for i, ref := range params.Refs {
oldValue := ref.Old
newValue := ref.New
if newValue.IsEmpty() { // replace all empty new values to the result of the merge
newValue = mergeCommitSHA
}
refUpdates[i] = hook.ReferenceUpdate{
Ref: ref.Name,
Old: oldValue,
New: newValue,
}
}
err = refUpdater.Init(ctx, refUpdates)
if err != nil {
return fmt.Errorf("failed to init values of references (%v): %w", refUpdates, err)
}
return nil
})
if errors.IsConflict(err) {
return MergeOutput{}, fmt.Errorf("failed to merge %q to %q in %q using the %q merge method: %w",
params.HeadBranch, params.BaseBranch, params.RepoUID, mergeMethod, err)
}
if err != nil {
return MergeOutput{}, fmt.Errorf("failed to merge %q to %q in %q using the %q merge method: %w",
params.HeadBranch, params.BaseBranch, params.RepoUID, mergeMethod, err)
}
if len(conflicts) > 0 {
return MergeOutput{
BaseSHA: baseCommitSHA,
HeadSHA: headCommitSHA,
MergeBaseSHA: mergeBaseCommitSHA,
MergeSHA: sha.None,
CommitCount: commitCount,
ChangedFileCount: shortStat.Files,
Additions: shortStat.Additions,
Deletions: shortStat.Deletions,
ConflictFiles: conflicts,
}, nil
}
return MergeOutput{
BaseSHA: baseCommitSHA,
HeadSHA: headCommitSHA,
MergeBaseSHA: mergeBaseCommitSHA,
MergeSHA: mergeCommitSHA,
CommitCount: commitCount,
ChangedFileCount: shortStat.Files,
Additions: shortStat.Additions,
Deletions: shortStat.Deletions,
ConflictFiles: nil,
}, nil
}
type MergeBaseParams struct {
ReadParams
Ref1 string
Ref2 string
}
func (p *MergeBaseParams) Validate() error {
if err := p.ReadParams.Validate(); err != nil {
return err
}
if p.Ref1 == "" {
// needs better naming
return errors.InvalidArgument("first reference cannot be empty")
}
if p.Ref2 == "" {
// needs better naming
return errors.InvalidArgument("second reference cannot be empty")
}
return nil
}
type MergeBaseOutput struct {
MergeBaseSHA sha.SHA
}
func (s *Service) MergeBase(
ctx context.Context,
params MergeBaseParams,
) (MergeBaseOutput, error) {
if err := params.Validate(); err != nil {
return MergeBaseOutput{}, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
result, _, err := s.git.GetMergeBase(ctx, repoPath, "", params.Ref1, params.Ref2, false)
if err != nil {
return MergeBaseOutput{}, err
}
return MergeBaseOutput{
MergeBaseSHA: result,
}, nil
}
type IsAncestorParams struct {
ReadParams
AncestorCommitSHA sha.SHA
DescendantCommitSHA sha.SHA
}
type IsAncestorOutput struct {
Ancestor bool
}
func (s *Service) IsAncestor(
ctx context.Context,
params IsAncestorParams,
) (IsAncestorOutput, error) {
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
result, err := s.git.IsAncestor(
ctx,
repoPath,
params.AlternateObjectDirs,
params.AncestorCommitSHA,
params.DescendantCommitSHA,
)
if err != nil {
return IsAncestorOutput{}, err
}
return IsAncestorOutput{
Ancestor: result,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/pre_receive_pre_processor.go | git/pre_receive_pre_processor.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"io"
"slices"
"strings"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/parser"
"github.com/harness/gitness/git/sha"
)
const (
maxOversizeFiles = 10
maxCommitterMismatches = 10
maxMissingLFSObjects = 10
)
type FindOversizeFilesParams struct {
// TODO: remove. Kept for backward compatibility
RepoUID string
GitObjectDirs []string
SizeLimit int64
}
type FileInfo struct {
SHA sha.SHA
Size int64
}
type FindOversizeFilesOutput struct {
FileInfos []FileInfo
Total int64
}
type FindCommitterMismatchParams struct {
PrincipalEmail string
}
type CommitInfo struct {
SHA sha.SHA
Committer string
}
type FindCommitterMismatchOutput struct {
CommitInfos []CommitInfo
Total int64
}
type FindLFSPointersParams struct {
ReadParams
}
type LFSInfo struct {
ObjID string
SHA sha.SHA
}
type FindLFSPointersOutput struct {
LFSInfos []LFSInfo
Total int64
}
type ProcessPreReceiveObjectsParams struct {
ReadParams
FindOversizeFilesParams *FindOversizeFilesParams
FindCommitterMismatchParams *FindCommitterMismatchParams
FindLFSPointersParams *FindLFSPointersParams
}
type ProcessPreReceiveObjectsOutput struct {
FindOversizeFilesOutput *FindOversizeFilesOutput
FindCommitterMismatchOutput *FindCommitterMismatchOutput
FindLFSPointersOutput *FindLFSPointersOutput
}
func (s *Service) ProcessPreReceiveObjects(
ctx context.Context,
params ProcessPreReceiveObjectsParams,
) (ProcessPreReceiveObjectsOutput, error) {
if params.FindOversizeFilesParams == nil && params.FindCommitterMismatchParams == nil &&
params.FindLFSPointersParams == nil {
return ProcessPreReceiveObjectsOutput{}, nil
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
var objects []parser.BatchCheckObject
for _, gitObjDir := range params.AlternateObjectDirs {
objs, err := s.listGitObjDir(ctx, repoPath, gitObjDir)
if err != nil {
return ProcessPreReceiveObjectsOutput{}, err
}
objects = append(objects, objs...)
}
// sort objects in descending order by Size (largest to smallest)
slices.SortFunc(objects, func(a, b parser.BatchCheckObject) int {
switch {
case a.Size > b.Size:
return -1
case a.Size < b.Size:
return 1
default:
return 0
}
})
var output ProcessPreReceiveObjectsOutput
if params.FindOversizeFilesParams != nil {
output.FindOversizeFilesOutput = findOversizeFiles(
objects, params.FindOversizeFilesParams,
)
}
if params.FindCommitterMismatchParams != nil {
out, err := findCommitterMismatch(
ctx,
objects,
repoPath,
params.ReadParams.AlternateObjectDirs,
params.FindCommitterMismatchParams,
)
if err != nil {
return ProcessPreReceiveObjectsOutput{}, err
}
output.FindCommitterMismatchOutput = out
}
if params.FindLFSPointersParams != nil {
out, err := s.findLFSPointers(
ctx,
objects,
repoPath,
params.ReadParams.AlternateObjectDirs,
params.FindLFSPointersParams,
)
if err != nil {
return ProcessPreReceiveObjectsOutput{}, err
}
output.FindLFSPointersOutput = out
}
return output, nil
}
func findOversizeFiles(
objects []parser.BatchCheckObject,
findOversizeFilesParams *FindOversizeFilesParams,
) *FindOversizeFilesOutput {
var fileInfos []FileInfo
var total int64 // limit the total num of objects returned
for _, obj := range objects {
if obj.Type == string(TreeNodeTypeBlob) && obj.Size > findOversizeFilesParams.SizeLimit {
if total < maxOversizeFiles {
fileInfos = append(fileInfos, FileInfo{
SHA: obj.SHA,
Size: obj.Size,
})
}
total++
}
}
return &FindOversizeFilesOutput{
FileInfos: fileInfos,
Total: total,
}
}
func findCommitterMismatch(
ctx context.Context,
objects []parser.BatchCheckObject,
repoPath string,
alternateObjectDirs []string,
findCommitterEmailsMismatchParams *FindCommitterMismatchParams,
) (*FindCommitterMismatchOutput, error) {
var commitSHAs []string
for _, obj := range objects {
if obj.Type == string(TreeNodeTypeCommit) {
commitSHAs = append(commitSHAs, obj.SHA.String())
}
}
writer, reader, cancel := api.CatFileBatch(ctx, repoPath, alternateObjectDirs)
defer cancel()
defer writer.Close()
var total int64
var commitInfos []CommitInfo
for _, commitSHA := range commitSHAs {
_, writeErr := writer.Write([]byte(commitSHA + "\n"))
if writeErr != nil {
return nil, fmt.Errorf("failed to write to cat-file batch: %w", writeErr)
}
output, err := api.ReadBatchHeaderLine(reader)
if err != nil {
return nil, fmt.Errorf("failed to read cat-file batch header: %w", err)
}
limitedReader := io.LimitReader(reader, output.Size+1) // plus eol
data, err := io.ReadAll(limitedReader)
if err != nil {
return nil, fmt.Errorf("failed to read: %w", err)
}
text := strings.SplitSeq(string(data), "\n")
for line := range text {
if !strings.HasPrefix(line, "committer ") {
continue
}
committerEmail := line[strings.Index(line, "<")+1 : strings.Index(line, ">")]
if !strings.EqualFold(committerEmail, findCommitterEmailsMismatchParams.PrincipalEmail) {
if total < maxCommitterMismatches {
sha, err := sha.New(commitSHA)
if err != nil {
return nil, fmt.Errorf("failed to create new sha: %w", err)
}
commitInfos = append(commitInfos, CommitInfo{
SHA: sha,
Committer: committerEmail,
})
}
total++
}
break
}
}
return &FindCommitterMismatchOutput{
CommitInfos: commitInfos,
Total: total,
}, nil
}
func (s *Service) findLFSPointers(
ctx context.Context,
objects []parser.BatchCheckObject,
repoPath string,
alternateObjectDirs []string,
_ *FindLFSPointersParams,
) (*FindLFSPointersOutput, error) {
var candidateObjects []parser.BatchCheckObject
for _, obj := range objects {
if obj.Type == string(TreeNodeTypeBlob) && obj.Size <= parser.LfsPointerMaxSize {
candidateObjects = append(candidateObjects, obj)
}
}
if len(candidateObjects) == 0 {
return &FindLFSPointersOutput{}, nil
}
// check the short-listed objects for lfs-pointers content
writer, reader, cancel := api.CatFileBatch(ctx, repoPath, alternateObjectDirs)
defer cancel()
var total int64
var lfsInfos []LFSInfo
for _, obj := range candidateObjects {
_, writeErr := writer.Write([]byte(obj.SHA.String() + "\n"))
if writeErr != nil {
return nil, fmt.Errorf("failed to write to cat-file batch: %w", writeErr)
}
// first line is always the object type, sha, and size
_, readErr := reader.ReadString('\n')
if readErr != nil {
return nil, fmt.Errorf("failed to read cat-file output: %w", readErr)
}
data, readErr := io.ReadAll(io.LimitReader(reader, obj.Size))
if readErr != nil {
return nil, fmt.Errorf("failed to read cat-file output: %w", readErr)
}
objID, err := parser.GetLFSObjectID(data)
if err != nil && !errors.Is(err, parser.ErrInvalidLFSPointer) {
return nil, fmt.Errorf("failed to parse cat-file output to get LFS object ID for sha %q: %w", obj.SHA, err)
}
if err == nil {
if total < maxMissingLFSObjects {
lfsInfos = append(lfsInfos, LFSInfo{ObjID: objID, SHA: obj.SHA})
}
total++
}
// skip the trailing new line
_, readErr = reader.ReadString('\n')
if readErr != nil {
return nil, fmt.Errorf("failed to read trailing newline after object: %w", readErr)
}
}
return &FindLFSPointersOutput{
LFSInfos: lfsInfos,
Total: total,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/blame.go | git/blame.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"io"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/sha"
)
type BlameParams struct {
ReadParams
GitRef string
Path string
// LineFrom allows to restrict the blame output to only lines starting from the provided line number (inclusive).
// Optional, ignored if value is 0.
LineFrom int
// LineTo allows to restrict the blame output to only lines up to the provided line number (inclusive).
// Optional, ignored if value is 0.
LineTo int
}
func (params *BlameParams) Validate() error {
if params == nil {
return ErrNoParamsProvided
}
if err := params.ReadParams.Validate(); err != nil {
return err
}
if params.GitRef == "" {
return errors.InvalidArgument("git ref needs to be provided")
}
if params.Path == "" {
return errors.InvalidArgument("file path needs to be provided")
}
if params.LineFrom < 0 || params.LineTo < 0 {
return errors.InvalidArgument("line from and line to can't be negative")
}
if params.LineTo > 0 && params.LineFrom > params.LineTo {
return errors.InvalidArgument("line from can't be after line after")
}
return nil
}
type BlamePart struct {
Commit *Commit `json:"commit"`
Lines []string `json:"lines"`
Previous *BlamePartPrevious `json:"previous,omitempty"`
}
type BlamePartPrevious struct {
CommitSHA sha.SHA `json:"commit_sha"`
FileName string `json:"file_name"`
}
// Blame processes and streams the git blame output data.
// The function returns two channels: The data channel and the error channel.
// If any error happens during the operation it will be put to the error channel
// and the streaming will stop. Maximum of one error can be put on the channel.
func (s *Service) Blame(ctx context.Context, params *BlameParams) (<-chan *BlamePart, <-chan error) {
ch := make(chan *BlamePart)
chErr := make(chan error, 1)
go func() {
defer close(ch)
defer close(chErr)
if err := params.Validate(); err != nil {
chErr <- err
return
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
reader := s.git.Blame(ctx,
repoPath, params.GitRef, params.Path,
params.LineFrom, params.LineTo)
for {
part, errRead := reader.NextPart()
if part == nil {
return
}
commit, err := mapCommit(part.Commit)
if err != nil {
chErr <- fmt.Errorf("failed to map rpc commit: %w", err)
return
}
lines := make([]string, len(part.Lines))
copy(lines, part.Lines)
next := &BlamePart{
Commit: commit,
Lines: lines,
}
if part.Previous != nil {
next.Previous = &BlamePartPrevious{
CommitSHA: part.Previous.CommitSHA,
FileName: part.Previous.FileName,
}
}
ch <- next
if errRead != nil && errors.Is(errRead, io.EOF) {
return
}
}
}()
return ch, chErr
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/wire.go | git/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"github.com/harness/gitness/cache"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/storage"
"github.com/harness/gitness/git/types"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideGITAdapter,
ProvideService,
)
func ProvideGITAdapter(
config types.Config,
lastCommitCache cache.Cache[api.CommitEntryKey, *api.Commit],
githookFactory hook.ClientFactory,
) (*api.Git, error) {
return api.New(
config,
lastCommitCache,
githookFactory,
)
}
func ProvideService(
config types.Config,
adapter *api.Git,
hookClientFactory hook.ClientFactory,
storage storage.Store,
) (Interface, error) {
return New(
config,
adapter,
hookClientFactory,
storage,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/sort.go | git/sort.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
type SortOrder int
const (
SortOrderDefault SortOrder = iota
SortOrderAsc = iota
SortOrderDesc
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/tree.go | git/tree.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
)
// TreeNodeType specifies the different types of nodes in a git tree.
// IMPORTANT: has to be consistent with rpc.TreeNodeType (proto).
type TreeNodeType string
const (
TreeNodeTypeTree TreeNodeType = "tree"
TreeNodeTypeBlob TreeNodeType = "blob"
TreeNodeTypeCommit TreeNodeType = "commit"
)
// TreeNodeMode specifies the different modes of a node in a git tree.
// IMPORTANT: has to be consistent with rpc.TreeNodeMode (proto).
type TreeNodeMode string
const (
TreeNodeModeFile TreeNodeMode = "file"
TreeNodeModeSymlink TreeNodeMode = "symlink"
TreeNodeModeExec TreeNodeMode = "exec"
TreeNodeModeTree TreeNodeMode = "tree"
TreeNodeModeCommit TreeNodeMode = "commit"
)
type TreeNode struct {
Type TreeNodeType
Mode TreeNodeMode
SHA string // TODO: make sha.SHA
Name string
Path string
}
type ListTreeNodeParams struct {
ReadParams
// GitREF is a git reference (branch / tag / commit SHA)
GitREF string
Path string
FlattenDirectories bool
}
type ListTreeNodeOutput struct {
Nodes []TreeNode
}
type GetTreeNodeParams struct {
ReadParams
// GitREF is a git reference (branch / tag / commit SHA)
GitREF string
Path string
IncludeLatestCommit bool
}
type GetTreeNodeOutput struct {
Node TreeNode
Commit *Commit
}
func (s *Service) GetTreeNode(ctx context.Context, params *GetTreeNodeParams) (*GetTreeNodeOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
gitNode, err := s.git.GetTreeNode(ctx, repoPath, params.GitREF, params.Path)
if err != nil {
return nil, fmt.Errorf("failed to find node '%s' in '%s': %w", params.Path, params.GitREF, err)
}
node, err := mapTreeNode(gitNode)
if err != nil {
return nil, fmt.Errorf("failed to map rpc node: %w", err)
}
if !params.IncludeLatestCommit {
return &GetTreeNodeOutput{
Node: node,
}, nil
}
pathDetails, err := s.git.PathsDetails(ctx, repoPath, params.GitREF, []string{params.Path})
if err != nil {
return nil, fmt.Errorf("failed to get path details for '%s' in '%s': %w", params.Path, params.GitREF, err)
}
if len(pathDetails) != 1 || pathDetails[0].LastCommit == nil {
return nil, fmt.Errorf("failed to get details for the path %s", params.Path)
}
var commit *Commit
if pathDetails[0].LastCommit != nil {
commit, err = mapCommit(pathDetails[0].LastCommit)
if err != nil {
return nil, fmt.Errorf("failed to map rpc commit: %w", err)
}
}
return &GetTreeNodeOutput{
Node: node,
Commit: commit,
}, nil
}
func (s *Service) ListTreeNodes(ctx context.Context, params *ListTreeNodeParams) (*ListTreeNodeOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
res, err := s.git.ListTreeNodes(ctx, repoPath, params.GitREF, params.Path, params.FlattenDirectories)
if err != nil {
return nil, fmt.Errorf("failed to list tree nodes: %w", err)
}
nodes := make([]TreeNode, len(res))
for i := range res {
n, err := mapTreeNode(&res[i])
if err != nil {
return nil, fmt.Errorf("failed to map rpc node: %w", err)
}
nodes[i] = n
}
return &ListTreeNodeOutput{
Nodes: nodes,
}, nil
}
type ListPathsParams struct {
ReadParams
// GitREF is a git reference (branch / tag / commit SHA)
GitREF string
IncludeDirectories bool
}
type ListPathsOutput struct {
Files []string
Directories []string
}
func (s *Service) ListPaths(ctx context.Context, params *ListPathsParams) (*ListPathsOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
files, dirs, err := s.git.ListPaths(
ctx,
repoPath,
params.GitREF,
params.IncludeDirectories,
)
if err != nil {
return nil, fmt.Errorf("failed to list paths: %w", err)
}
return &ListPathsOutput{
Files: files,
Directories: dirs,
},
nil
}
type PathsDetailsParams struct {
ReadParams
GitREF string
Paths []string
}
type PathsDetailsOutput struct {
Details []PathDetails
}
type PathDetails struct {
Path string `json:"path"`
LastCommit *Commit `json:"last_commit,omitempty"`
}
func (s *Service) PathsDetails(ctx context.Context, params PathsDetailsParams) (PathsDetailsOutput, error) {
if err := params.Validate(); err != nil {
return PathsDetailsOutput{}, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
pathsDetails, err := s.git.PathsDetails(
ctx,
repoPath,
params.GitREF,
params.Paths)
if err != nil {
return PathsDetailsOutput{}, fmt.Errorf("failed to get path details in '%s': %w", params.GitREF, err)
}
details := make([]PathDetails, len(pathsDetails))
for i, pathDetail := range pathsDetails {
var lastCommit *Commit
if pathDetail.LastCommit != nil {
lastCommit, err = mapCommit(pathDetail.LastCommit)
if err != nil {
return PathsDetailsOutput{}, fmt.Errorf("failed to map last commit: %w", err)
}
}
details[i] = PathDetails{
Path: pathDetail.Path,
LastCommit: lastCommit,
}
}
return PathsDetailsOutput{
Details: details,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/commit.go | git/commit.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"bytes"
"context"
"fmt"
"io/fs"
"os"
"time"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/command"
"github.com/harness/gitness/git/enum"
"github.com/harness/gitness/git/parser"
"github.com/harness/gitness/git/sha"
)
func CommitMessage(subject, body string) string {
if body == "" {
return subject
}
return subject + "\n\n" + body
}
type GetCommitParams struct {
ReadParams
Revision string
IgnoreWhitespace bool
}
type Commit struct {
SHA sha.SHA `json:"sha"`
TreeSHA sha.SHA `json:"-"`
ParentSHAs []sha.SHA `json:"parent_shas,omitempty"`
Title string `json:"title"`
Message string `json:"message,omitempty"`
Author Signature `json:"author"`
Committer Signature `json:"committer"`
SignedData *SignedData `json:"-"`
FileStats []CommitFileStats `json:"file_stats,omitempty"`
}
type GetCommitOutput struct {
Commit Commit `json:"commit"`
}
type Signature struct {
Identity Identity `json:"identity"`
When time.Time `json:"when"`
}
func (s *Signature) String() string {
return s.Identity.String() + " " + s.When.String()
}
type Identity struct {
Name string `json:"name"`
Email string `json:"email"`
}
func (i *Identity) String() string {
return fmt.Sprintf("%s <%s>", i.Name, i.Email)
}
func (i *Identity) Validate() error {
if i.Name == "" {
return errors.InvalidArgument("identity name is mandatory")
}
if i.Email == "" {
return errors.InvalidArgument("identity email is mandatory")
}
return nil
}
func (s *Service) GetCommit(ctx context.Context, params *GetCommitParams) (*GetCommitOutput, error) {
if params == nil {
return nil, ErrNoParamsProvided
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
result, err := s.git.GetCommitFromRev(ctx, repoPath, params.Revision)
if err != nil {
return nil, err
}
commit, err := mapCommit(result)
if err != nil {
return nil, fmt.Errorf("failed to map rpc commit: %w", err)
}
return &GetCommitOutput{
Commit: *commit,
}, nil
}
type ListCommitsParams struct {
ReadParams
// GitREF is a git reference (branch / tag / commit SHA)
GitREF string
// After is a git reference (branch / tag / commit SHA)
// If provided, commits only up to that reference will be returned (exlusive)
After string
Page int32
Limit int32
Path string
// Since allows to filter for commits since the provided UNIX timestamp - Optional, ignored if value is 0.
Since int64
// Until allows to filter for commits until the provided UNIX timestamp - Optional, ignored if value is 0.
Until int64
// Committer allows to filter for commits based on the committer - Optional, ignored if string is empty.
Committer string
// Author allows to filter for commits based on the author - Optional, ignored if string is empty.
Author string
// IncludeStats allows to include information about inserted, deletions and status for changed files.
IncludeStats bool
// Regex allows to use regular expression in the Committer and Author fields
Regex bool
}
type RenameDetails struct {
OldPath string
NewPath string
CommitShaBefore sha.SHA
CommitShaAfter sha.SHA
}
type ListCommitsOutput struct {
Commits []Commit
RenameDetails []*RenameDetails
TotalCommits int
}
type CommitFileStats struct {
Status enum.FileDiffStatus
Path string
OldPath string // populated only in case of renames
Insertions int64
Deletions int64
}
func (s *Service) ListCommits(ctx context.Context, params *ListCommitsParams) (*ListCommitsOutput, error) {
if params == nil {
return nil, ErrNoParamsProvided
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
gitCommits, renameDetails, err := s.git.ListCommits(
ctx,
repoPath,
params.GitREF,
int(params.Page),
int(params.Limit),
params.IncludeStats,
api.CommitFilter{
AfterRef: params.After,
Path: params.Path,
Since: params.Since,
Until: params.Until,
Committer: params.Committer,
Author: params.Author,
Regex: params.Regex,
},
)
if err != nil {
return nil, err
}
// try to get total commits between gitref and After refs
totalCommits := 0
if params.Page == 1 && len(gitCommits) < int(params.Limit) {
totalCommits = len(gitCommits)
} else if params.After != "" && params.GitREF != params.After {
div, err := s.git.GetCommitDivergences(ctx, repoPath, []api.CommitDivergenceRequest{
{From: params.GitREF, To: params.After},
}, 0)
if err != nil {
return nil, err
}
if len(div) > 0 {
totalCommits = int(div[0].Ahead)
}
}
commits := make([]Commit, len(gitCommits))
for i := range gitCommits {
commit, err := mapCommit(&gitCommits[i])
if err != nil {
return nil, fmt.Errorf("failed to map rpc commit: %w", err)
}
commits[i] = *commit
}
return &ListCommitsOutput{
Commits: commits,
RenameDetails: mapRenameDetails(renameDetails),
TotalCommits: totalCommits,
}, nil
}
type GetCommitDivergencesParams struct {
ReadParams
MaxCount int32
Requests []CommitDivergenceRequest
}
type GetCommitDivergencesOutput struct {
Divergences []api.CommitDivergence
}
// CommitDivergenceRequest contains the refs for which the converging commits should be counted.
type CommitDivergenceRequest struct {
// From is the ref from which the counting of the diverging commits starts.
From string
// To is the ref at which the counting of the diverging commits ends.
To string
}
// CommitDivergence contains the information of the count of converging commits between two refs.
type CommitDivergence struct {
// Ahead is the count of commits the 'From' ref is ahead of the 'To' ref.
Ahead int32
// Behind is the count of commits the 'From' ref is behind the 'To' ref.
Behind int32
}
func (s *Service) GetCommitDivergences(
ctx context.Context,
params *GetCommitDivergencesParams,
) (*GetCommitDivergencesOutput, error) {
if params == nil {
return nil, ErrNoParamsProvided
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
requests := make([]api.CommitDivergenceRequest, len(params.Requests))
for i, req := range params.Requests {
requests[i] = api.CommitDivergenceRequest{
From: req.From,
To: req.To,
}
}
divergences, err := s.git.GetCommitDivergences(
ctx,
repoPath,
requests,
params.MaxCount,
)
if err != nil {
return nil, err
}
return &GetCommitDivergencesOutput{
Divergences: divergences,
}, nil
}
// TODO: remove. Kept for backwards compatibility.
//
//nolint:gocognit
func (s *Service) FindOversizeFiles(
ctx context.Context,
params *FindOversizeFilesParams,
) (*FindOversizeFilesOutput, error) {
if params.RepoUID == "" {
return nil, api.ErrRepositoryPathEmpty
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
var objects []parser.BatchCheckObject
for _, gitObjDir := range params.GitObjectDirs {
objs, err := s.listGitObjDir(ctx, repoPath, gitObjDir)
if err != nil {
return nil, err
}
objects = append(objects, objs...)
}
var fileInfos []FileInfo
for _, obj := range objects {
if obj.Type == string(TreeNodeTypeBlob) && obj.Size > params.SizeLimit {
fileInfos = append(fileInfos, FileInfo{
SHA: obj.SHA,
Size: obj.Size,
})
}
}
return &FindOversizeFilesOutput{
FileInfos: fileInfos,
}, nil
}
func (s *Service) listGitObjDir(
ctx context.Context,
repoPath string,
gitObjDir string,
) ([]parser.BatchCheckObject, error) {
// "info/alternates" points to the original repository.
const oldFilename = "/info/alternates"
const newFilename = "/info/alternates.bkp"
// --batch-all-objects reports objects in the current repository and in all alternate directories.
// We want to report objects in the current repository only.
if err := os.Rename(gitObjDir+oldFilename, gitObjDir+newFilename); err != nil &&
!errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("failed to rename %s to %s: %w", oldFilename, newFilename, err)
}
cmd := command.New("cat-file",
command.WithFlag("--batch-check"),
command.WithFlag("--batch-all-objects"),
command.WithFlag("--unordered"),
command.WithFlag("-Z"),
command.WithEnv(command.GitObjectDir, gitObjDir),
)
buffer := bytes.NewBuffer(nil)
err := cmd.Run(
ctx,
command.WithDir(repoPath),
command.WithStdout(buffer),
)
if err != nil {
return nil, fmt.Errorf("failed to cat-file batch check all objects: %w", err)
}
objects, err := parser.CatFileBatchCheckAllObjects(buffer)
if err != nil {
return nil, fmt.Errorf("failed to parse output of cat-file batch check all objects: %w", err)
}
if err := os.Rename(gitObjDir+newFilename, gitObjDir+oldFilename); err != nil &&
!errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("failed to rename %s to %s: %w", newFilename, oldFilename, err)
}
return objects, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/ref.go | git/ref.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"math"
"strings"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/enum"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/sha"
)
type GetRefParams struct {
ReadParams
Name string
Type enum.RefType
}
func (p *GetRefParams) Validate() error {
if p == nil {
return ErrNoParamsProvided
}
if err := p.ReadParams.Validate(); err != nil {
return err
}
if p.Name == "" {
return errors.InvalidArgument("ref name cannot be empty")
}
return nil
}
type GetRefResponse struct {
SHA sha.SHA
}
func (s *Service) GetRef(ctx context.Context, params GetRefParams) (GetRefResponse, error) {
if err := params.Validate(); err != nil {
return GetRefResponse{}, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
reference, err := GetRefPath(params.Name, params.Type)
if err != nil {
return GetRefResponse{}, fmt.Errorf("GetRef: failed to fetch reference '%s': %w", params.Name, err)
}
refSHA, err := s.git.GetRef(ctx, repoPath, reference)
if err != nil {
return GetRefResponse{}, err
}
return GetRefResponse{SHA: refSHA}, nil
}
type UpdateRefParams struct {
WriteParams
Type enum.RefType
Name string
// NewValue specified the new value the reference should point at.
// An empty value will lead to the deletion of the branch.
NewValue sha.SHA
// OldValue is an optional value that can be used to ensure that the reference
// is updated iff its current value is matching the provided value.
OldValue sha.SHA
}
func (s *Service) UpdateRef(ctx context.Context, params UpdateRefParams) error {
if err := params.Validate(); err != nil {
return err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
reference, err := GetRefPath(params.Name, params.Type)
if err != nil {
return fmt.Errorf("failed to create reference '%s': %w", params.Name, err)
}
refUpdater, err := hook.CreateRefUpdater(s.hookClientFactory, params.EnvVars, repoPath)
if err != nil {
return fmt.Errorf("failed to create ref updater: %w", err)
}
if err := refUpdater.DoOne(ctx, reference, params.OldValue, params.NewValue); err != nil {
return fmt.Errorf("failed to update ref: %w", err)
}
return nil
}
func GetRefPath(refName string, refType enum.RefType) (string, error) {
const (
refPullReqPrefix = "refs/pullreq/"
refPullReqHeadSuffix = "/head"
refPullReqMergeSuffix = "/merge"
)
switch refType {
case enum.RefTypeRaw:
return refName, nil
case enum.RefTypeBranch:
return api.BranchPrefix + refName, nil
case enum.RefTypeTag:
return api.TagPrefix + refName, nil
case enum.RefTypePullReqHead:
return refPullReqPrefix + refName + refPullReqHeadSuffix, nil
case enum.RefTypePullReqMerge:
return refPullReqPrefix + refName + refPullReqMergeSuffix, nil
default:
return "", errors.InvalidArgumentf("provided reference type '%s' is invalid", refType)
}
}
// wrapInstructorWithOptionalPagination wraps the provided walkInstructor with pagination.
// If no paging is enabled, the original instructor is returned.
func wrapInstructorWithOptionalPagination(
inner api.WalkReferencesInstructor,
page int32,
pageSize int32,
) (api.WalkReferencesInstructor, int32, error) {
// ensure pagination is requested
if pageSize < 1 {
return inner, 0, nil
}
// sanitize page
if page < 1 {
page = 1
}
// ensure we don't overflow
if int64(page)*int64(pageSize) > int64(math.MaxInt) {
return nil, 0, fmt.Errorf("page %d with pageSize %d is out of range", page, pageSize)
}
startAfter := (page - 1) * pageSize
endAfter := page * pageSize
// we have to count ourselves for proper pagination
c := int32(0)
return func(e api.WalkReferencesEntry) (api.WalkInstruction, error) {
// execute inner instructor
inst, err := inner(e)
if err != nil {
return inst, err
}
// no pagination if element is filtered out
if inst != api.WalkInstructionHandle {
return inst, nil
}
// increase count iff element is part of filtered output
c++
// add pagination on filtered output
switch {
case c <= startAfter:
return api.WalkInstructionSkip, nil
case c > endAfter:
return api.WalkInstructionStop, nil
default:
return api.WalkInstructionHandle, nil
}
},
endAfter,
nil
}
// createReferenceWalkPatternsFromQuery returns a list of patterns that
// ensure only references matching the basePath and query are part of the walk.
func createReferenceWalkPatternsFromQuery(basePath string, query string) []string {
if basePath == "" && query == "" {
return []string{}
}
// ensure non-empty basepath ends with "/" for proper matching and concatenation.
if basePath != "" && basePath[len(basePath)-1] != '/' {
basePath += "/"
}
// in case query is empty, we just match the basePath.
if query == "" {
return []string{basePath}
}
// sanitze the query and get special chars
query, matchPrefix, matchSuffix := sanitizeReferenceQuery(query)
// In general, there are two search patterns:
// - refs/tags/**/*QUERY* - finds all refs that have QUERY in the filename.
// - refs/tags/**/*QUERY*/** - finds all refs that have a parent folder with QUERY in the name.
//
// In case the suffix has to match, they will be the same, so we return only one pattern.
if matchSuffix {
// exact match (refs/tags/QUERY)
if matchPrefix {
return []string{basePath + query}
}
// suffix only match (refs/tags/**/*QUERY)
//nolint:goconst
return []string{basePath + "**/*" + query}
}
// prefix only match
// - refs/tags/QUERY*
// - refs/tags/QUERY*/**
if matchPrefix {
return []string{
basePath + query + "*", // file
basePath + query + "*/**", // folder
}
}
// arbitrary match
// - refs/tags/**/*QUERY*
// - refs/tags/**/*QUERY*/**
return []string{
basePath + "**/*" + query + "*", // file
basePath + "**/*" + query + "*/**", // folder
}
}
// sanitizeReferenceQuery removes characters that aren't allowd in a branch name.
// TODO: should we error out instead of ignore bad chars?
func sanitizeReferenceQuery(query string) (string, bool, bool) {
if query == "" {
return "", false, false
}
// get special characters before anything else
matchPrefix := query[0] == '^' // will be removed by mapping
matchSuffix := query[len(query)-1] == '$'
if matchSuffix {
// Special char $ has to be removed manually as it's a valid char
// TODO: this restricts the query language to a certain degree, can we do better? (escaping)
query = query[:len(query)-1]
}
// strip all unwanted characters
return strings.Map(func(r rune) rune {
// See https://git-scm.com/docs/git-check-ref-format#_description for more details.
switch {
// rule 4.
case r < 32 || r == 127 || r == ' ' || r == '~' || r == '^' || r == ':':
return -1
// rule 5
case r == '?' || r == '*' || r == '[':
return -1
// everything else we map as is
default:
return r
}
}, query),
matchPrefix,
matchSuffix
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/revert.go | git/revert.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"os"
"time"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
gitenum "github.com/harness/gitness/git/enum"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/parser"
"github.com/harness/gitness/git/sha"
"github.com/harness/gitness/git/sharedrepo"
"github.com/rs/zerolog/log"
)
// RevertParams is input structure object for the revert operation.
type RevertParams struct {
WriteParams
ParentCommitSHA sha.SHA
FromCommitSHA sha.SHA
ToCommitSHA sha.SHA
RevertBranch string
Message string
Committer *Identity
CommitterDate *time.Time
Author *Identity
AuthorDate *time.Time
}
func (p *RevertParams) Validate() error {
if err := p.WriteParams.Validate(); err != nil {
return err
}
if p.Message == "" {
return errors.InvalidArgument("commit message is empty")
}
if p.RevertBranch == "" {
return errors.InvalidArgument("revert branch is missing")
}
return nil
}
type RevertOutput struct {
CommitSHA sha.SHA
}
// Revert creates a revert commit. The revert commit contains all changes introduced
// by the commits between params.FromCommitSHA and params.ToCommitSHA.
// The newly created commit will have the parent set as params.ParentCommitSHA.
// This method can be used to revert a pull request:
// * params.ParentCommit = pr.MergeSHA
// * params.FromCommitSHA = pr.MergeBaseSHA
// * params.ToCommitSHA = pr.SourceSHA.
func (s *Service) Revert(ctx context.Context, params *RevertParams) (RevertOutput, error) {
err := params.Validate()
if err != nil {
return RevertOutput{}, fmt.Errorf("params not valid: %w", err)
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
// Check the merge base commit of the FromCommit and the ToCommit.
// We expect that the merge base would be equal to the FromCommit.
// This guaranties that the FromCommit is an ancestor of the ToCommit
// and that the two commits have simple commit history.
// The diff could be found with the simple 'git diff',
// rather than going though the merge base with 'git diff --merge-base'.
if params.FromCommitSHA.Equal(params.ToCommitSHA) {
return RevertOutput{}, errors.InvalidArgument("from and to commits can't be the same commit.")
}
mergeBaseCommitSHA, _, err := s.git.GetMergeBase(ctx, repoPath, "origin",
params.FromCommitSHA.String(), params.ToCommitSHA.String(), false)
if err != nil {
return RevertOutput{}, fmt.Errorf("failed to get merge base: %w", err)
}
if !params.FromCommitSHA.Equal(mergeBaseCommitSHA) {
return RevertOutput{}, errors.InvalidArgument("from and to commits must not branch out.")
}
// Set the author and the committer. The rules for setting these are the same as for the Merge method.
now := time.Now().UTC()
committer := api.Signature{Identity: api.Identity(params.Actor), When: now}
if params.Committer != nil {
committer.Identity = api.Identity(*params.Committer)
}
if params.CommitterDate != nil {
committer.When = *params.CommitterDate
}
author := committer
if params.Author != nil {
author.Identity = api.Identity(*params.Author)
}
if params.AuthorDate != nil {
author.When = *params.AuthorDate
}
// Prepare the message for the revert commit.
message := parser.CleanUpWhitespace(params.Message)
// Reference updater
refRevertBranch, err := GetRefPath(params.RevertBranch, gitenum.RefTypeBranch)
if err != nil {
return RevertOutput{}, fmt.Errorf("failed to generate revert branch ref name: %w", err)
}
refUpdater, err := hook.CreateRefUpdater(s.hookClientFactory, params.EnvVars, repoPath)
if err != nil {
return RevertOutput{}, fmt.Errorf("failed to create reference updater: %w", err)
}
// Temp file to hold the diff patch.
diffPatch, err := os.CreateTemp(s.sharedRepoRoot, "revert-*.patch")
if err != nil {
return RevertOutput{}, fmt.Errorf("failed to create temporary file to hold the diff patch: %w", err)
}
diffPatchName := diffPatch.Name()
defer func() {
if err = os.Remove(diffPatchName); err != nil {
log.Ctx(ctx).Warn().Err(err).Str("path", diffPatchName).Msg("failed to remove temp file")
}
}()
// Create the revert commit
var commitSHA sha.SHA
err = sharedrepo.Run(ctx, refUpdater, s.sharedRepoRoot, repoPath, func(s *sharedrepo.SharedRepo) error {
if err := s.WriteDiff(ctx, params.ToCommitSHA.String(), params.FromCommitSHA.String(), diffPatch); err != nil {
return fmt.Errorf("failed to find diff between the two commits: %w", err)
}
if err := diffPatch.Close(); err != nil {
return fmt.Errorf("failed to close patch file: %w", err)
}
fInfo, err := os.Lstat(diffPatchName)
if err != nil {
return fmt.Errorf("failed to lstat diff path file: %w", err)
}
if fInfo.Size() == 0 {
return errors.InvalidArgument("can't revert an empty diff")
}
if err := s.SetIndex(ctx, params.ParentCommitSHA); err != nil {
return fmt.Errorf("failed to set parent commit index: %w", err)
}
if err := s.ApplyToIndex(ctx, diffPatchName); err != nil {
return fmt.Errorf("failed to apply revert diff: %w", err)
}
treeSHA, err := s.WriteTree(ctx)
if err != nil {
return fmt.Errorf("failed to write revert tree: %w", err)
}
commitSHA, err = s.CommitTree(ctx, &author, &committer, treeSHA, message, false, params.ParentCommitSHA)
if err != nil {
return fmt.Errorf("failed to create revert commit: %w", err)
}
refUpdates := []hook.ReferenceUpdate{
{
Ref: refRevertBranch,
Old: sha.Nil, // Expect that the revert branch doesn't exist.
New: commitSHA,
},
}
err = refUpdater.Init(ctx, refUpdates)
if err != nil {
return fmt.Errorf("failed to set init value of the revert reference %s: %w", refRevertBranch, err)
}
return nil
})
if err != nil {
return RevertOutput{}, fmt.Errorf("failed to revert: %w", err)
}
return RevertOutput{
CommitSHA: commitSHA,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/stream.go | git/stream.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import "io"
// StreamReader is a helper utility to ease reading from streaming channel pair (the data and the error channel).
type StreamReader[T any] struct {
chData <-chan T
chErr <-chan error
}
// NewStreamReader creates new StreamReader.
func NewStreamReader[T any](chData <-chan T, chErr <-chan error) *StreamReader[T] {
return &StreamReader[T]{
chData: chData,
chErr: chErr,
}
}
// Next returns the next element or error.
// In case the end has been reached, an io.EOF is returned.
func (str *StreamReader[T]) Next() (T, error) {
var null T
select {
case data, ok := <-str.chData:
if !ok {
return null, io.EOF
}
return data, nil
case err, ok := <-str.chErr:
if !ok {
return null, io.EOF
}
return null, err
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/path.go | git/path.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"fmt"
"path/filepath"
)
const (
gitRepoSuffix = "git"
)
// getFullPathForRepo returns the full path of a repo given the root dir of repos and the uid of the repo.
// NOTE: Split repos into subfolders using their prefix to distribute repos across a set of folders.
func getFullPathForRepo(reposRoot, uid string) string {
// ASSUMPTION: repoUID is of lenth at least 4 - otherwise we have trouble either way.
return filepath.Join(
reposRoot, // root folder
uid[0:2], // first subfolder
uid[2:4], // second subfolder
fmt.Sprintf("%s.%s", uid[4:], gitRepoSuffix), // remainder with .git
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/validate.go | git/validate.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import "regexp"
var matchCommitSHA = regexp.MustCompile("^[0-9a-f]+$")
func ValidateCommitSHA(commitSHA string) bool {
if len(commitSHA) != 40 && len(commitSHA) != 64 {
return false
}
return matchCommitSHA.MatchString(commitSHA)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/revision.go | git/revision.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"github.com/harness/gitness/git/sha"
)
type ResolveRevisionParams struct {
ReadParams
Revision string
}
type ResolveRevisionOutput struct {
SHA sha.SHA
}
func (s *Service) ResolveRevision(ctx context.Context, params ResolveRevisionParams) (ResolveRevisionOutput, error) {
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
resolvedSHA, err := s.git.ResolveRev(ctx, repoPath, params.Revision)
if err != nil {
return ResolveRevisionOutput{}, fmt.Errorf("failed to resolve revision: %w", err)
}
return ResolveRevisionOutput{
SHA: resolvedSHA,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/summary.go | git/summary.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/merge"
"golang.org/x/sync/errgroup"
)
type SummaryParams struct {
ReadParams
}
type SummaryOutput struct {
CommitCount int
BranchCount int
TagCount int
}
func (s *Service) Summary(
ctx context.Context,
params SummaryParams,
) (SummaryOutput, error) {
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
defaultBranch, err := s.git.GetDefaultBranch(ctx, repoPath)
if err != nil {
return SummaryOutput{}, err
}
defaultBranchRef := api.GetReferenceFromBranchName(defaultBranch)
g, ctx := errgroup.WithContext(ctx)
var commitCount, branchCount, tagCount int
g.Go(func() error {
var err error
commitCount, err = merge.CommitCount(ctx, repoPath, "", defaultBranchRef)
return err
})
g.Go(func() error {
var err error
branchCount, err = s.git.GetBranchCount(ctx, repoPath)
return err
})
g.Go(func() error {
var err error
tagCount, err = s.git.GetTagCount(ctx, repoPath)
return err
})
if err := g.Wait(); err != nil {
return SummaryOutput{}, fmt.Errorf("failed to get repo summary: %w", err)
}
return SummaryOutput{
CommitCount: commitCount,
BranchCount: branchCount,
TagCount: tagCount,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/service.go | git/service.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"fmt"
"os"
"path/filepath"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/storage"
"github.com/harness/gitness/git/types"
)
const (
repoSubdirName = "repos"
repoSharedRepoSubdirName = "shared_temp"
ReposGraveyardSubdirName = "cleanup"
)
type Service struct {
reposRoot string
sharedRepoRoot string
git *api.Git
hookClientFactory hook.ClientFactory
store storage.Store
gitHookPath string
reposGraveyard string
}
func New(
config types.Config,
adapter *api.Git,
hookClientFactory hook.ClientFactory,
storage storage.Store,
) (*Service, error) {
// Create repos folder
reposRoot, err := createSubdir(config.Root, repoSubdirName)
if err != nil {
return nil, err
}
// create a temp dir for deleted repositories
// this dir should get cleaned up peridocally if it's not empty
reposGraveyard, err := createSubdir(config.Root, ReposGraveyardSubdirName)
if err != nil {
return nil, err
}
sharedRepoDir, err := createSubdir(config.Root, repoSharedRepoSubdirName)
if err != nil {
return nil, err
}
return &Service{
reposRoot: reposRoot,
sharedRepoRoot: sharedRepoDir,
reposGraveyard: reposGraveyard,
git: adapter,
hookClientFactory: hookClientFactory,
store: storage,
gitHookPath: config.HookPath,
}, nil
}
func createSubdir(root, subdir string) (string, error) {
subdirPath := filepath.Join(root, subdir)
err := os.MkdirAll(subdirPath, fileMode700)
if err != nil {
return "", fmt.Errorf("failed to create directory, path=%s: %w", subdirPath, err)
}
return subdirPath, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/errors.go | git/errors.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"github.com/harness/gitness/errors"
)
var (
ErrNoParamsProvided = errors.InvalidArgument("params not provided")
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/interface.go | git/interface.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"io"
"github.com/harness/gitness/git/api"
)
type Interface interface {
CreateRepository(ctx context.Context, params *CreateRepositoryParams) (*CreateRepositoryOutput, error)
DeleteRepository(ctx context.Context, params *DeleteRepositoryParams) error
GetTreeNode(ctx context.Context, params *GetTreeNodeParams) (*GetTreeNodeOutput, error)
ListTreeNodes(ctx context.Context, params *ListTreeNodeParams) (*ListTreeNodeOutput, error)
ListPaths(ctx context.Context, params *ListPathsParams) (*ListPathsOutput, error)
GetSubmodule(ctx context.Context, params *GetSubmoduleParams) (*GetSubmoduleOutput, error)
GetBlob(ctx context.Context, params *GetBlobParams) (*GetBlobOutput, error)
CreateBranch(ctx context.Context, params *CreateBranchParams) (*CreateBranchOutput, error)
CreateCommitTag(ctx context.Context, params *CreateCommitTagParams) (*CreateCommitTagOutput, error)
DeleteTag(ctx context.Context, params *DeleteTagParams) error
GetBranch(ctx context.Context, params *GetBranchParams) (*GetBranchOutput, error)
DeleteBranch(ctx context.Context, params *DeleteBranchParams) error
ListBranches(ctx context.Context, params *ListBranchesParams) (*ListBranchesOutput, error)
UpdateDefaultBranch(ctx context.Context, params *UpdateDefaultBranchParams) error
GetRef(ctx context.Context, params GetRefParams) (GetRefResponse, error)
PathsDetails(ctx context.Context, params PathsDetailsParams) (PathsDetailsOutput, error)
Summary(ctx context.Context, params SummaryParams) (SummaryOutput, error)
FindLFSPointers(ctx context.Context, params *FindLFSPointersParams) (*FindLFSPointersOutput, error)
// GetRepositorySize calculates the size of a repo in KiB.
GetRepositorySize(ctx context.Context, params *GetRepositorySizeParams) (*GetRepositorySizeOutput, error)
// UpdateRef creates, updates or deletes a git ref. If the OldValue is defined it must match the reference value
// prior to the call. To remove a ref use the zero ref as the NewValue. To require the creation of a new one and
// not update of an exiting one, set the zero ref as the OldValue.
UpdateRef(ctx context.Context, params UpdateRefParams) error
SyncRepository(ctx context.Context, params *SyncRepositoryParams) (*SyncRepositoryOutput, error)
SyncRefs(ctx context.Context, params *SyncRefsParams) (*SyncRefsOutput, error)
FetchObjects(ctx context.Context, params *FetchObjectsParams) (FetchObjectsOutput, error)
GetRemoteDefaultBranch(
ctx context.Context,
params *GetRemoteDefaultBranchParams,
) (*GetRemoteDefaultBranchOutput, error)
MatchFiles(ctx context.Context, params *MatchFilesParams) (*MatchFilesOutput, error)
/*
* Commits service
*/
GetCommit(ctx context.Context, params *GetCommitParams) (*GetCommitOutput, error)
ListCommits(ctx context.Context, params *ListCommitsParams) (*ListCommitsOutput, error)
ListCommitTags(ctx context.Context, params *ListCommitTagsParams) (*ListCommitTagsOutput, error)
GetCommitDivergences(ctx context.Context, params *GetCommitDivergencesParams) (*GetCommitDivergencesOutput, error)
CommitFiles(ctx context.Context, params *CommitFilesParams) (CommitFilesResponse, error)
MergeBase(ctx context.Context, params MergeBaseParams) (MergeBaseOutput, error)
IsAncestor(ctx context.Context, params IsAncestorParams) (IsAncestorOutput, error)
// TODO: remove. Kept for backwards compatibility.
FindOversizeFiles(
ctx context.Context,
params *FindOversizeFilesParams,
) (*FindOversizeFilesOutput, error)
/*
* Pre-receive processor
*/
ProcessPreReceiveObjects(
ctx context.Context,
params ProcessPreReceiveObjectsParams,
) (ProcessPreReceiveObjectsOutput, error)
/*
* Git Cli Service
*/
GetInfoRefs(ctx context.Context, w io.Writer, params *InfoRefsParams) error
ServicePack(ctx context.Context, params *ServicePackParams) error
/*
* Diff services
*/
RawDiff(ctx context.Context, w io.Writer, in *DiffParams, files ...api.FileDiffRequest) error
Diff(ctx context.Context, in *DiffParams, files ...api.FileDiffRequest) (<-chan *FileDiff, <-chan error)
DiffFileNames(ctx context.Context, in *DiffParams) (DiffFileNamesOutput, error)
CommitDiff(ctx context.Context, params *GetCommitParams, w io.Writer) error
DiffShortStat(ctx context.Context, params *DiffParams) (DiffShortStatOutput, error)
DiffStats(ctx context.Context, params *DiffParams) (DiffStatsOutput, error)
GetDiffHunkHeaders(ctx context.Context, params GetDiffHunkHeadersParams) (GetDiffHunkHeadersOutput, error)
DiffCut(ctx context.Context, params *DiffCutParams) (DiffCutOutput, error)
ResolveRevision(ctx context.Context, params ResolveRevisionParams) (ResolveRevisionOutput, error)
/*
* Merge services
*/
Merge(ctx context.Context, in *MergeParams) (MergeOutput, error)
Revert(ctx context.Context, in *RevertParams) (RevertOutput, error)
/*
* Blame services
*/
Blame(ctx context.Context, params *BlameParams) (<-chan *BlamePart, <-chan error)
PushRemote(ctx context.Context, params *PushRemoteParams) error
GeneratePipeline(ctx context.Context, params *GeneratePipelineParams) (GeneratePipelinesOutput, error)
/*
* Secret Scanning service
*/
ScanSecrets(ctx context.Context, param *ScanSecretsParams) (*ScanSecretsOutput, error)
Archive(ctx context.Context, params ArchiveParams, w io.Writer) error
/*
* Repository optimizer
*/
OptimizeRepository(ctx context.Context, params OptimizeRepositoryParams) error
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/params.go | git/params.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
type Repository interface {
GetGitUID() string
}
// CreateReadParams creates base read parameters for git read operations.
// IMPORTANT: repo is assumed to be not nil!
func CreateReadParams(repo Repository) ReadParams {
return ReadParams{
RepoUID: repo.GetGitUID(),
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/optimize_test.go | git/optimize_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"testing"
"time"
"github.com/harness/gitness/git/api"
"github.com/gotidy/ptr"
"github.com/stretchr/testify/require"
)
func TestParseGCArgs(t *testing.T) {
now := time.Now().Truncate(time.Second)
rfcDate := now.Format(api.RFC2822DateFormat)
parsedDate, _ := time.Parse(api.RFC2822DateFormat, rfcDate)
tests := []struct {
name string
args map[string]string
expected api.GCParams
}{
{
name: "All fields valid",
args: map[string]string{
"aggressive": "true",
"auto": "false",
"cruft": "true",
"max-cruft-size": "123456",
"prune": rfcDate,
"keep-largest-pack": "true",
},
expected: api.GCParams{
Aggressive: true,
Auto: false,
Cruft: ptr.Bool(true),
MaxCruftSize: 123456,
Prune: parsedDate,
KeepLargestPack: true,
},
},
{
name: "Prune as bool",
args: map[string]string{
"prune": "false",
},
expected: api.GCParams{
Prune: ptr.Bool(false),
},
},
{
name: "Prune as fallback string",
args: map[string]string{
"prune": "2.weeks.ago",
},
expected: api.GCParams{
Prune: "2.weeks.ago",
},
},
{
name: "Invalid bools ignored",
args: map[string]string{
"aggressive": "yes",
"keep-largest-pack": "maybe",
"cruft": "idk",
},
expected: api.GCParams{},
},
{
name: "Invalid max-cruft-size ignored",
args: map[string]string{
"max-cruft-size": "not-a-number",
},
expected: api.GCParams{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := parseGCArgs(tt.args)
require.Equal(t, tt.expected.Aggressive, result.Aggressive)
require.Equal(t, tt.expected.Auto, result.Auto)
require.Equal(t, tt.expected.KeepLargestPack, result.KeepLargestPack)
require.Equal(t, tt.expected.MaxCruftSize, result.MaxCruftSize)
if tt.expected.Cruft != nil {
require.NotNil(t, result.Cruft)
require.Equal(t, *tt.expected.Cruft, *result.Cruft)
} else {
require.Nil(t, result.Cruft)
}
switch expected := tt.expected.Prune.(type) {
case time.Time:
actualTime, ok := result.Prune.(time.Time)
require.True(t, ok)
require.True(t, actualTime.Equal(expected))
case *bool:
actualBool, ok := result.Prune.(*bool)
require.True(t, ok)
require.Equal(t, *expected, *actualBool)
case string:
require.Equal(t, expected, result.Prune)
case nil:
require.Nil(t, result.Prune)
default:
t.Fatalf("unsupported prune type: %T", expected)
}
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/operations.go | git/operations.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"strings"
"time"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/parser"
"github.com/harness/gitness/git/sha"
"github.com/harness/gitness/git/sharedrepo"
)
const (
filePermissionDefault = "100644"
)
type FileAction string
const (
CreateAction FileAction = "CREATE"
UpdateAction FileAction = "UPDATE"
DeleteAction FileAction = "DELETE"
MoveAction FileAction = "MOVE"
PatchTextAction FileAction = "PATCH_TEXT"
)
func (FileAction) Enum() []any {
return []any{CreateAction, UpdateAction, DeleteAction, MoveAction, PatchTextAction}
}
// CommitFileAction holds file operation data.
type CommitFileAction struct {
Action FileAction
Path string
Payload []byte
SHA sha.SHA
}
// CommitFilesParams holds the data for file operations.
type CommitFilesParams struct {
WriteParams
Title string // Deprecated
Message string
Branch string
NewBranch string
Actions []CommitFileAction
// Committer overwrites the git committer used for committing the files
// (optional, default: actor)
Committer *Identity
// CommitterDate overwrites the git committer date used for committing the files
// (optional, default: current time on server)
CommitterDate *time.Time
// Author overwrites the git author used for committing the files
// (optional, default: committer)
Author *Identity
// AuthorDate overwrites the git author date used for committing the files
// (optional, default: committer date)
AuthorDate *time.Time
}
func (p *CommitFilesParams) Validate() error {
return p.WriteParams.Validate()
}
type FileReference struct {
Path string
SHA sha.SHA
}
type CommitFilesResponse struct {
CommitID sha.SHA
ChangedFiles []FileReference
}
//nolint:gocognit,nestif
func (s *Service) CommitFiles(ctx context.Context, params *CommitFilesParams) (CommitFilesResponse, error) {
if err := params.Validate(); err != nil {
return CommitFilesResponse{}, err
}
committer := params.Actor
if params.Committer != nil {
committer = *params.Committer
}
committerDate := time.Now().UTC()
if params.CommitterDate != nil {
committerDate = *params.CommitterDate
}
author := committer
if params.Author != nil {
author = *params.Author
}
authorDate := committerDate
if params.AuthorDate != nil {
authorDate = *params.AuthorDate
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
// check if repo is empty
// IMPORTANT: we don't use gitea's repo.IsEmpty() as that only checks whether the default branch exists (in HEAD).
// This can be an issue in case someone created a branch already in the repo (just default branch is missing).
// In that case the user can accidentally create separate git histories (which most likely is unintended).
// If the user wants to actually build a disconnected commit graph they can use the cli.
isEmpty, err := s.git.HasBranches(ctx, repoPath)
if err != nil {
return CommitFilesResponse{}, fmt.Errorf("CommitFiles: failed to determine if repository is empty: %w", err)
}
// validate and prepare input
// ensure input data is valid
// the commit will be nil for empty repositories
commit, err := s.validateAndPrepareCommitFilesHeader(ctx, repoPath, isEmpty, params)
if err != nil {
return CommitFilesResponse{}, err
}
// ref updater
var refOldSHA sha.SHA
var refNewSHA sha.SHA
var changedFiles []FileReference
branchRef := api.GetReferenceFromBranchName(params.Branch)
if params.Branch != params.NewBranch {
// we are creating a new branch, rather than updating the existing one
refOldSHA = sha.Nil
branchRef = api.GetReferenceFromBranchName(params.NewBranch)
} else if commit != nil {
refOldSHA = commit.SHA
}
refUpdater, err := hook.CreateRefUpdater(s.hookClientFactory, params.EnvVars, repoPath)
if err != nil {
return CommitFilesResponse{}, fmt.Errorf("failed to create ref updater: %w", err)
}
// run the actions in a shared repo
err = sharedrepo.Run(ctx, refUpdater, s.sharedRepoRoot, repoPath, func(r *sharedrepo.SharedRepo) error {
var parentCommits []sha.SHA
var oldTreeSHA sha.SHA
if isEmpty {
oldTreeSHA = sha.EmptyTree
changedFiles, err = s.prepareTreeEmptyRepo(ctx, r, params.Actions)
if err != nil {
return fmt.Errorf("failed to prepare empty tree: %w", err)
}
} else {
parentCommits = append(parentCommits, commit.SHA)
// get tree sha
rootNode, err := s.git.GetTreeNode(ctx, repoPath, commit.SHA.String(), "")
if err != nil {
return fmt.Errorf("CommitFiles: failed to get original node: %w", err)
}
oldTreeSHA = rootNode.SHA
err = r.SetIndex(ctx, commit.SHA)
if err != nil {
return fmt.Errorf("failed to set index in shared repository: %w", err)
}
changedFiles, err = s.prepareTree(ctx, r, commit.SHA, params.Actions)
if err != nil {
return fmt.Errorf("failed to prepare tree: %w", err)
}
}
treeSHA, err := r.WriteTree(ctx)
if err != nil {
return fmt.Errorf("failed to write tree object: %w", err)
}
if oldTreeSHA.Equal(treeSHA) {
return errors.InvalidArgument("No effective changes.")
}
authorSig := &api.Signature{
Identity: api.Identity{
Name: author.Name,
Email: author.Email,
},
When: authorDate,
}
committerSig := &api.Signature{
Identity: api.Identity{
Name: committer.Name,
Email: committer.Email,
},
When: committerDate,
}
var message string
if params.Title != "" {
// Title is deprecated and should not be sent, but if it's sent assume we need to generate the full message.
message = parser.CleanUpWhitespace(CommitMessage(params.Title, params.Message))
} else {
message = parser.CleanUpWhitespace(params.Message)
}
commitSHA, err := r.CommitTree(ctx, authorSig, committerSig, treeSHA, message, false, parentCommits...)
if err != nil {
return fmt.Errorf("failed to commit the tree: %w", err)
}
refNewSHA = commitSHA
ref := hook.ReferenceUpdate{
Ref: branchRef,
Old: refOldSHA,
New: refNewSHA,
}
if err := refUpdater.Init(ctx, []hook.ReferenceUpdate{ref}); err != nil {
return fmt.Errorf("failed to init ref updater old=%s new=%s: %w", refOldSHA, refNewSHA, err)
}
return nil
})
if err != nil {
return CommitFilesResponse{}, fmt.Errorf("CommitFiles: failed to create commit in shared repository: %w", err)
}
return CommitFilesResponse{
CommitID: refNewSHA,
ChangedFiles: changedFiles,
}, nil
}
func (s *Service) prepareTree(
ctx context.Context,
r *sharedrepo.SharedRepo,
treeishSHA sha.SHA,
actions []CommitFileAction,
) ([]FileReference, error) {
// patch file actions are executed in batch for a single file
patchMap := map[string][]*CommitFileAction{}
// keep track of what paths have been written to detect conflicting actions
modifiedPaths := map[string]bool{}
fileRefs := make([]FileReference, 0, len(actions))
for i := range actions {
act := &actions[i]
// patch text actions are executed in per-file batches.
if act.Action == PatchTextAction {
patchMap[act.Path] = append(patchMap[act.Path], act)
continue
}
// anything else is executed as is
modifiedPath, objectSHA, err := s.processAction(ctx, r, treeishSHA, act)
if err != nil {
return nil, fmt.Errorf("failed to process action %s on %q: %w", act.Action, act.Path, err)
}
if modifiedPaths[modifiedPath] {
return nil, errors.InvalidArgumentf("More than one conflicting actions are modifying file %q.", modifiedPath)
}
fileRefs = append(fileRefs, FileReference{
Path: modifiedPath,
SHA: objectSHA,
})
modifiedPaths[modifiedPath] = true
}
for filePath, patchActions := range patchMap {
// combine input across actions
var fileSHA sha.SHA
var payloads [][]byte
for _, act := range patchActions {
payloads = append(payloads, act.Payload)
if fileSHA.IsEmpty() {
fileSHA = act.SHA
continue
}
// there can only be one file sha for a given path and commit.
if !act.SHA.IsEmpty() && !fileSHA.Equal(act.SHA) {
return nil, errors.InvalidArgumentf(
"patch text actions for %q contain different SHAs %q and %q",
filePath,
act.SHA,
fileSHA,
)
}
}
objectSHA, err := r.PatchTextFile(ctx, treeishSHA, filePath, fileSHA, payloads)
if err != nil {
return nil, fmt.Errorf("failed to process action %s on %q: %w", PatchTextAction, filePath, err)
}
if modifiedPaths[filePath] {
return nil, errors.InvalidArgumentf("More than one conflicting action are modifying file %q.", filePath)
}
fileRefs = append(fileRefs, FileReference{
Path: filePath,
SHA: objectSHA,
})
modifiedPaths[filePath] = true
}
return fileRefs, nil
}
func (s *Service) prepareTreeEmptyRepo(
ctx context.Context,
r *sharedrepo.SharedRepo,
actions []CommitFileAction,
) ([]FileReference, error) {
fileRefs := make([]FileReference, 0, len(actions))
for _, action := range actions {
if action.Action != CreateAction {
return nil, errors.PreconditionFailed("action not allowed on empty repository")
}
filePath := api.CleanUploadFileName(action.Path)
if filePath == "" {
return nil, errors.InvalidArgument("invalid path")
}
objectSHA, err := r.CreateFile(ctx, sha.None, filePath, filePermissionDefault, action.Payload)
if err != nil {
return nil, errors.Internalf(err, "failed to create file '%s'", action.Path)
}
fileRefs = append(fileRefs, FileReference{
Path: filePath,
SHA: objectSHA,
})
}
return fileRefs, nil
}
func (s *Service) validateAndPrepareCommitFilesHeader(
ctx context.Context,
repoPath string,
isEmpty bool,
params *CommitFilesParams,
) (*api.Commit, error) {
if params.Branch == "" {
defaultBranchRef, err := s.git.GetDefaultBranch(ctx, repoPath)
if err != nil {
return nil, fmt.Errorf("failed to get default branch: %w", err)
}
params.Branch = defaultBranchRef
}
if params.NewBranch == "" {
params.NewBranch = params.Branch
}
// trim refs/heads/ prefixes to avoid issues when calling gitea API
params.Branch = strings.TrimPrefix(strings.TrimSpace(params.Branch), gitReferenceNamePrefixBranch)
params.NewBranch = strings.TrimPrefix(strings.TrimSpace(params.NewBranch), gitReferenceNamePrefixBranch)
// if the repo is empty then we can skip branch existence checks
if isEmpty {
return nil, nil //nolint:nilnil // an empty repository has no commit and there's no error
}
// ensure source branch exists
branch, err := s.git.GetBranch(ctx, repoPath, params.Branch)
if err != nil {
return nil, fmt.Errorf("failed to get source branch '%s': %w", params.Branch, err)
}
// ensure new branch doesn't exist yet (if new branch creation was requested)
if params.Branch != params.NewBranch {
existingBranch, err := s.git.GetBranch(ctx, repoPath, params.NewBranch)
if existingBranch != nil {
return nil, errors.Conflictf("branch %s already exists", existingBranch.Name)
}
if err != nil && !errors.IsNotFound(err) {
return nil, fmt.Errorf("failed to create new branch '%s': %w", params.NewBranch, err)
}
}
return branch.Commit, nil
}
func (s *Service) processAction(
ctx context.Context,
r *sharedrepo.SharedRepo,
treeishSHA sha.SHA,
action *CommitFileAction,
) (modifiedPath string, objectSHA sha.SHA, err error) {
filePath := api.CleanUploadFileName(action.Path)
if filePath == "" {
return "", sha.None, errors.InvalidArgument("path cannot be empty")
}
modifiedPath = filePath
switch action.Action {
case CreateAction:
objectSHA, err = r.CreateFile(ctx, treeishSHA, filePath, filePermissionDefault, action.Payload)
case UpdateAction:
objectSHA, err = r.UpdateFile(ctx, treeishSHA, filePath, action.SHA, filePermissionDefault, action.Payload)
case MoveAction:
modifiedPath, objectSHA, err =
r.MoveFile(ctx, treeishSHA, filePath, action.SHA, filePermissionDefault, action.Payload)
case DeleteAction:
err = r.DeleteFile(ctx, filePath)
case PatchTextAction:
return "", sha.None, fmt.Errorf("action %s not supported by this method", action.Action)
default:
err = fmt.Errorf("unknown file action %q", action.Action)
}
return modifiedPath, objectSHA, err
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/scan_secrets.go | git/scan_secrets.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"io"
"os"
"path"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/sharedrepo"
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
const (
DefaultGitleaksIgnorePath = ".gitleaksignore"
)
type ScanSecretsParams struct {
ReadParams
BaseRev string // optional to scan for secrets on diff between baseRev and Rev
Rev string
GitleaksIgnorePath string // optional, keep empty to skip using .gitleaksignore file.
}
type ScanSecretsOutput struct {
Findings []ScanSecretsFinding
}
type ScanSecretsFinding struct {
Description string `json:"description"`
StartLine int64 `json:"start_line"`
EndLine int64 `json:"end_line"`
StartColumn int64 `json:"start_column"`
EndColumn int64 `json:"end_column"`
Match string `json:"match"`
Secret string `json:"secret"`
File string `json:"file"`
SymlinkFile string `json:"symlink_file"`
Commit string `json:"commit"`
Entropy float64 `json:"entropy"`
Author string `json:"author"`
Email string `json:"email"`
Date string `json:"date"`
Message string `json:"message"`
Tags []string `json:"tags"`
RuleID string `json:"rule_id"`
// Fingerprint is the unique identifier of the secret that can be used in .gitleaksignore files.
Fingerprint string `json:"fingerprint"`
}
func (s *Service) ScanSecrets(ctx context.Context, params *ScanSecretsParams) (*ScanSecretsOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
var findings []ScanSecretsFinding
err := sharedrepo.Run(ctx, nil, s.sharedRepoRoot, repoPath, func(sharedRepo *sharedrepo.SharedRepo) error {
fsGitleaksIgnorePath, err := s.setupGitleaksIgnoreInSharedRepo(
ctx,
sharedRepo,
params.Rev,
params.GitleaksIgnorePath,
)
if err != nil {
return fmt.Errorf("failed to setup .gitleaksignore file in share repo: %w", err)
}
detector, err := detect.NewDetectorDefaultConfig()
if err != nil {
return fmt.Errorf("failed to create a new gitleaks detector with default config: %w", err)
}
if fsGitleaksIgnorePath != "" {
if err := detector.AddGitleaksIgnore(fsGitleaksIgnorePath); err != nil {
return fmt.Errorf("failed to load .gitleaksignore file from path %q: %w", fsGitleaksIgnorePath, err)
}
}
// TODO: fix issue where secrets in second-parent commits are not detected
logOpts := fmt.Sprintf("--no-merges --first-parent %s", params.Rev)
if params.BaseRev != "" {
logOpts = fmt.Sprintf("--no-merges --first-parent %s..%s", params.BaseRev, params.Rev)
}
gitCmd, err := sources.NewGitLogCmd(sharedRepo.Directory(), logOpts)
if err != nil {
return fmt.Errorf("failed to create a new git log cmd with diff: %w", err)
}
res, err := detector.DetectGit(gitCmd)
if err != nil {
return fmt.Errorf("failed to detect git leaks on diff: %w", err)
}
findings = mapFindings(res)
return nil
}, params.AlternateObjectDirs...)
if err != nil {
return nil, fmt.Errorf("failed to get leaks on diff: %w", err)
}
return &ScanSecretsOutput{
Findings: findings,
}, nil
}
func (s *Service) setupGitleaksIgnoreInSharedRepo(
ctx context.Context,
sharedRepo *sharedrepo.SharedRepo,
rev string,
treePath string,
) (string, error) {
if treePath == "" {
log.Ctx(ctx).Debug().Msgf("no path to .gitleaksignore file provided, run without")
return "", nil
}
// ensure file exists in tree for the provided revision, otherwise ignore and continue
node, err := s.git.GetTreeNode(ctx, sharedRepo.Directory(), rev, treePath)
if errors.IsNotFound(err) {
log.Ctx(ctx).Debug().Msgf("no .gitleaksignore file found at %q, run without", treePath)
return "", nil
}
if err != nil {
return "", fmt.Errorf("failed to get tree node for .gitleaksignore file at path %q: %w", treePath, err)
}
// if node isn't of type blob it won't contain any gitleaks related content - run without .gitleaksignore.
// NOTE: We don't do any further checks for binary files or handle symlinks.
if node.NodeType != api.TreeNodeTypeBlob {
log.Ctx(ctx).Warn().Msgf(
"tree node at path %q is of type %d instead of %d (blob), run without .gitleaksignore",
treePath,
node.NodeType,
api.TreeNodeTypeBlob,
)
return "", nil
}
log.Ctx(ctx).Debug().Msgf(".gitleaksignore file found in tree at %q", treePath)
// read blob data from bare repo
blob, err := api.GetBlob(
ctx,
sharedRepo.Directory(),
nil,
node.SHA,
0,
)
if err != nil {
return "", fmt.Errorf(
"failed to get blob for .gitleaksignore file at path %q sha %q: %w", treePath, node.SHA, err)
}
defer func() {
if err := blob.Content.Close(); err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf("failed to close blob content reader for .gitleaksignore file")
}
}()
// write file to root of .git folder of the shared repo for easy cleanup (it's a bare repo so otherwise no impact)
filePath := path.Join(sharedRepo.Directory(), DefaultGitleaksIgnorePath)
f, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return "", fmt.Errorf("failed to create tmp .gitleaksignore file: %w", err)
}
defer func() {
if err := f.Close(); err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf("failed to close tmp .gitleaksignore file at %q", filePath)
}
}()
_, err = io.Copy(f, blob.Content)
if err != nil {
return "", fmt.Errorf("failed to copy .gitleaksignore file from blob to %q: %w", filePath, err)
}
return filePath, nil
}
func mapFindings(reports []report.Finding) []ScanSecretsFinding {
var findings []ScanSecretsFinding
for _, f := range reports {
findings = append(findings, ScanSecretsFinding{
Description: f.Description,
StartLine: int64(f.StartLine),
EndLine: int64(f.EndLine),
StartColumn: int64(f.StartColumn),
EndColumn: int64(f.EndColumn),
Match: f.Match,
Secret: f.Secret,
File: f.File,
SymlinkFile: f.SymlinkFile,
Commit: f.Commit,
Entropy: float64(f.Entropy),
Author: f.Author,
Email: f.Email,
Date: f.Date,
Message: f.Message,
Tags: f.Tags,
RuleID: f.RuleID,
Fingerprint: f.Fingerprint,
})
}
return findings
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/repo.go | git/repo.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"io"
"io/fs"
"maps"
"os"
"path"
"runtime/debug"
"slices"
"strings"
"time"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/check"
"github.com/harness/gitness/git/hash"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/sha"
"github.com/harness/gitness/git/sharedrepo"
gonanoid "github.com/matoous/go-nanoid/v2"
"github.com/rs/zerolog/log"
)
const (
// repoGitUIDLength is the length of the generated repo uid.
repoGitUIDLength = 42
// repoGitUIDAlphabet is the alphabet used for generating repo uids
// NOTE: keep it lowercase and alphanumerical to avoid issues with case insensitive filesystems.
repoGitUIDAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
gitReferenceNamePrefixBranch = "refs/heads/"
gitReferenceNamePrefixTag = "refs/tags/"
gitHooksDir = "hooks"
fileMode700 = 0o700
)
var (
gitServerHookNames = []string{
"pre-receive",
// "update", // update is disabled for performance reasons (called once for every ref)
"post-receive",
}
)
type CreateRepositoryParams struct {
// Create operation is different from all (from user side), as UID doesn't exist yet.
// Only take actor and envars as input and create WriteParams manually
RepoUID string
Actor Identity
EnvVars map[string]string
DefaultBranch string
Files []File
// Committer overwrites the git committer used for committing the files
// (optional, default: actor)
Committer *Identity
// CommitterDate overwrites the git committer date used for committing the files
// (optional, default: current time on server)
CommitterDate *time.Time
// Author overwrites the git author used for committing the files
// (optional, default: committer)
Author *Identity
// AuthorDate overwrites the git author date used for committing the files
// (optional, default: committer date)
AuthorDate *time.Time
}
func (p *CreateRepositoryParams) Validate() error {
return p.Actor.Validate()
}
type CreateRepositoryOutput struct {
UID string
}
type DeleteRepositoryParams struct {
WriteParams
}
type GetRepositorySizeParams struct {
ReadParams
}
type GetRepositorySizeOutput struct {
// Total size of the repository in KiB.
Size int64
}
type SyncRepositoryParams struct {
WriteParams
Source string
CreateIfNotExists bool
// RefSpecs [OPTIONAL] allows to override the refspecs that are being synced from the remote repository.
// By default all references present on the remote repository will be fetched (including scm internal ones).
RefSpecs []string
// DefaultBranch [OPTIONAL] allows to override the default branch of the repository.
// If empty, the default branch will be set to match the remote repository's default branch.
// WARNING: If the remote repo is empty and no value is provided, an api.ErrNoDefaultBranch error is returned.
DefaultBranch string
}
type SyncRepositoryOutput struct {
DefaultBranch string
}
type HashRepositoryParams struct {
ReadParams
HashType hash.Type
AggregationType hash.AggregationType
}
func (p *HashRepositoryParams) Validate() error {
return p.ReadParams.Validate()
}
type HashRepositoryOutput struct {
Hash []byte
}
type UpdateDefaultBranchParams struct {
WriteParams
// BranchName is the name of the branch (not the full reference).
BranchName string
}
type GetDefaultBranchParams struct {
ReadParams
}
type GetDefaultBranchOutput struct {
// BranchName is the name of the branch (not the full reference).
BranchName string
}
func (s *Service) CreateRepository(
ctx context.Context,
params *CreateRepositoryParams,
) (*CreateRepositoryOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
log := log.Ctx(ctx)
if params.RepoUID == "" {
uid, err := NewRepositoryUID()
if err != nil {
return nil, fmt.Errorf("failed to create new uid: %w", err)
}
params.RepoUID = uid
}
log.Info().
Msgf("Create new git repository with uid '%s' and default branch '%s'", params.RepoUID, params.DefaultBranch)
writeParams := WriteParams{
RepoUID: params.RepoUID,
Actor: params.Actor,
EnvVars: params.EnvVars,
}
committer := params.Actor
if params.Committer != nil {
committer = *params.Committer
}
committerDate := time.Now().UTC()
if params.CommitterDate != nil {
committerDate = *params.CommitterDate
}
author := committer
if params.Author != nil {
author = *params.Author
}
authorDate := committerDate
if params.AuthorDate != nil {
authorDate = *params.AuthorDate
}
err := s.createRepositoryInternal(
ctx,
&writeParams,
params.DefaultBranch,
params.Files,
&committer,
committerDate,
&author,
authorDate,
)
if err != nil {
return nil, err
}
return &CreateRepositoryOutput{
UID: params.RepoUID,
}, nil
}
func NewRepositoryUID() (string, error) {
return gonanoid.Generate(repoGitUIDAlphabet, repoGitUIDLength)
}
func (s *Service) DeleteRepository(ctx context.Context, params *DeleteRepositoryParams) error {
if err := params.Validate(); err != nil {
return err
}
return s.DeleteRepositoryBestEffort(ctx, params.RepoUID)
}
func (s *Service) DeleteRepositoryBestEffort(ctx context.Context, repoUID string) error {
repoPath := getFullPathForRepo(s.reposRoot, repoUID)
tempPath := path.Join(s.reposGraveyard, repoUID)
// delete should not fail if repoGraveyard dir does not exist.
if _, err := os.Stat(s.reposGraveyard); errors.Is(err, fs.ErrNotExist) {
if errdir := os.MkdirAll(s.reposGraveyard, fileMode700); errdir != nil {
return fmt.Errorf("clean up dir '%s' doesn't exist and can't be created: %w", s.reposGraveyard, errdir)
}
}
// move current dir to a temp dir (prevent partial deletion)
err := os.Rename(repoPath, tempPath)
if errors.Is(err, fs.ErrNotExist) {
return errors.NotFound("repository path not found") // caller decides whether ignore this error
}
if err != nil {
return fmt.Errorf("couldn't move dir %s to %s : %w", repoPath, tempPath, err)
}
if err := os.RemoveAll(tempPath); err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf("failed to delete dir %s from graveyard", tempPath)
}
return nil
}
func (s *Service) SyncRepository(
ctx context.Context,
params *SyncRepositoryParams,
) (*SyncRepositoryOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
source := s.convertRepoSource(params.Source)
// create repo if requested
_, err := os.Stat(repoPath)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, errors.Internal(err, "failed to create repository")
}
if errors.Is(err, fs.ErrNotExist) {
if !params.CreateIfNotExists {
return nil, errors.NotFound("repository not found")
}
// the default branch doesn't matter for a sync,
// we create an empty repo and the head will by updated later.
const syncDefaultBranch = "main"
if err = s.createRepositoryInternal(
ctx,
¶ms.WriteParams,
syncDefaultBranch,
nil,
nil,
time.Time{},
nil,
time.Time{},
); err != nil {
return nil, err
}
}
// sync repo content
err = s.git.Sync(ctx, repoPath, source, params.RefSpecs)
if err != nil {
return nil, fmt.Errorf("failed to sync from source repo: %w", err)
}
defaultBranch := params.DefaultBranch
if defaultBranch == "" {
// get default branch from remote repo (returns api.ErrNoDefaultBranch if repo is empty!)
defaultBranch, err = s.git.GetRemoteDefaultBranch(ctx, source)
if err != nil {
return nil, fmt.Errorf("failed to get default branch from source repo: %w", err)
}
}
// set default branch
err = s.git.SetDefaultBranch(ctx, repoPath, defaultBranch, true)
if err != nil {
return nil, fmt.Errorf("failed to set default branch of repo: %w", err)
}
return &SyncRepositoryOutput{
DefaultBranch: defaultBranch,
}, nil
}
func (s *Service) HashRepository(ctx context.Context, params *HashRepositoryParams) (*HashRepositoryOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
// add all references of the repo to the channel in a separate go routine, to allow streamed processing.
// Ensure we cancel the go routine in case we exit the func early.
goCtx, cancel := context.WithCancel(ctx)
defer cancel()
hashChan := make(chan hash.SourceNext)
go func() {
// always close channel last before leaving go routine
defer close(hashChan)
defer func() {
if r := recover(); r != nil {
hashChan <- hash.SourceNext{
Err: fmt.Errorf("panic received while filling data source: %s", debug.Stack()),
}
}
}()
// add default branch to hash
// IMPORTANT: Has to stay as is to ensure hash consistency! (e.g. "refs/heads/main/n")
defaultBranchRef, err := s.git.GetSymbolicRefHeadRaw(goCtx, repoPath)
if err != nil {
hashChan <- hash.SourceNext{
Err: fmt.Errorf("HashRepository: failed to get default branch: %w", err),
}
return
}
hashChan <- hash.SourceNext{
Data: hash.SerializeHead(defaultBranchRef),
}
err = s.git.WalkReferences(goCtx, repoPath, func(wre api.WalkReferencesEntry) error {
ref, ok := wre[api.GitReferenceFieldRefName]
if !ok {
return errors.New("ref entry didn't contain the ref name")
}
sha, ok := wre[api.GitReferenceFieldObjectName]
if !ok {
return errors.New("ref entry didn't contain the ref object sha")
}
hashChan <- hash.SourceNext{
Data: hash.SerializeReference(ref, sha),
}
return nil
}, &api.WalkReferencesOptions{})
if err != nil {
hashChan <- hash.SourceNext{
Err: fmt.Errorf("HashRepository: failed to walk references: %w", err),
}
}
}()
hasher, err := hash.New(params.HashType, params.AggregationType)
if err != nil {
return nil, fmt.Errorf("HashRepository: failed to get new reference hasher: %w", err)
}
source := hash.SourceFromChannel(ctx, hashChan)
res, err := hasher.Hash(source)
if err != nil {
return nil, fmt.Errorf("HashRepository: failed to hash repository: %w", err)
}
return &HashRepositoryOutput{
Hash: res,
}, nil
}
//nolint:gocognit // refactor if needed
func (s *Service) createRepositoryInternal(
ctx context.Context,
base *WriteParams,
defaultBranch string,
files []File,
committer *Identity,
committerDate time.Time,
author *Identity,
authorDate time.Time,
) error {
log := log.Ctx(ctx)
repoPath := getFullPathForRepo(s.reposRoot, base.RepoUID)
if _, err := os.Stat(repoPath); !errors.Is(err, fs.ErrNotExist) {
return errors.Conflictf("repository already exists at path %q", repoPath)
}
// create repository in repos folder
ctx, cancel := context.WithCancel(ctx)
defer cancel()
err := s.git.InitRepository(ctx, repoPath, true)
// delete repo dir on error
defer func() {
if err != nil {
cleanuperr := s.DeleteRepositoryBestEffort(ctx, base.RepoUID)
if cleanuperr != nil && !errors.IsNotFound(cleanuperr) {
log.Warn().Err(cleanuperr).Msg("failed to cleanup repo dir")
}
}
}()
if err != nil {
return fmt.Errorf("createRepositoryInternal: failed to initialize the repository: %w", err)
}
// update default branch (currently set to non-existent branch)
err = s.git.SetDefaultBranch(ctx, repoPath, defaultBranch, true)
if err != nil {
return fmt.Errorf("createRepositoryInternal: error updating default branch for repo '%s': %w",
base.RepoUID, err)
}
// only execute file creation logic if files are provided
//nolint: nestif
// we need temp dir for cloning
tempDir, err := os.MkdirTemp("", "*-"+base.RepoUID)
if err != nil {
return fmt.Errorf("error creating temp dir for repo %s: %w", base.RepoUID, err)
}
defer func(path string) {
// when repo is successfully created remove temp dir
errRm := os.RemoveAll(path)
if errRm != nil {
log.Err(errRm).Msg("failed to cleanup temporary dir.")
}
}(tempDir)
// Clone repository to temp dir
if err = s.git.Clone(ctx, repoPath, tempDir, api.CloneRepoOptions{}); err != nil {
return fmt.Errorf("createRepositoryInternal: failed to clone repo: %w", err)
}
// logic for receiving files
filePaths := make([]string, 0, 16)
for _, file := range files {
var filePath string
filePath, err = s.handleFileUploadIfAvailable(ctx, tempDir, file)
if errors.Is(err, io.EOF) {
log.Info().Msg("received stream EOF")
break
}
if err != nil {
return errors.Internalf(err, "failed to receive file %s", file)
}
filePaths = append(filePaths, filePath)
}
if len(filePaths) > 0 {
if committer == nil {
committer = &base.Actor
}
if author == nil {
author = committer
}
// NOTE: This creates the branch in origin repo (as it doesn't exist as of now)
// TODO: this should at least be a constant and not hardcoded?
if err = s.addFilesAndPush(ctx,
tempDir,
filePaths, "HEAD:"+defaultBranch,
nil,
author,
authorDate,
committer,
committerDate,
"origin",
"initial commit",
); err != nil {
return err
}
}
// setup server hook symlinks pointing to configured server hook binary
// IMPORTANT: Setup hooks after repo creation to avoid issues with externally dependent services.
for _, hook := range gitServerHookNames {
hookPath := path.Join(repoPath, gitHooksDir, hook)
err = os.Symlink(s.gitHookPath, hookPath)
if err != nil {
return errors.Internalf(err, "failed to setup symlink for hook '%s' ('%s' -> '%s')",
hook, hookPath, s.gitHookPath)
}
}
log.Info().Msgf("repository created. Path: %s", repoPath)
return nil
}
// GetRepositorySize accumulates the sizes of counted Git objects.
func (s *Service) GetRepositorySize(
ctx context.Context,
params *GetRepositorySizeParams,
) (*GetRepositorySizeOutput, error) {
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
count, err := s.git.CountObjects(ctx, repoPath)
if err != nil {
return nil, fmt.Errorf("failed to count objects for repo: %w", err)
}
return &GetRepositorySizeOutput{
Size: count.Size + count.SizePack,
}, nil
}
// GetDefaultBranch returns the default branch of the repo.
func (s *Service) GetDefaultBranch(
ctx context.Context,
params *GetDefaultBranchParams,
) (*GetDefaultBranchOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
dfltBranch, err := s.git.GetDefaultBranch(ctx, repoPath)
if err != nil {
return nil, fmt.Errorf("failed to get repo default branch: %w", err)
}
return &GetDefaultBranchOutput{
BranchName: dfltBranch,
}, nil
}
// UpdateDefaultBranch updates the default branch of the repo.
func (s *Service) UpdateDefaultBranch(
ctx context.Context,
params *UpdateDefaultBranchParams,
) error {
if err := params.Validate(); err != nil {
return err
}
if err := check.BranchName(params.BranchName); err != nil {
return errors.InvalidArgument(err.Error())
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
err := s.git.SetDefaultBranch(ctx, repoPath, params.BranchName, false)
if err != nil {
return fmt.Errorf("failed to update repo default branch %q: %w",
params.BranchName, err)
}
return nil
}
type ArchiveParams struct {
ReadParams
api.ArchiveParams
}
func (p *ArchiveParams) Validate() error {
if err := p.ReadParams.Validate(); err != nil {
return err
}
//nolint:revive
if err := p.ArchiveParams.Validate(); err != nil {
return err
}
return nil
}
func (s *Service) Archive(ctx context.Context, params ArchiveParams, w io.Writer) error {
if err := params.Validate(); err != nil {
return err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
err := s.git.Archive(ctx, repoPath, params.ArchiveParams, w)
if err != nil {
return fmt.Errorf("failed to run git archive: %w", err)
}
return nil
}
type FetchObjectsParams struct {
WriteParams
Source string
ObjectSHAs []sha.SHA
}
type FetchObjectsOutput struct{}
func (s *Service) FetchObjects(
ctx context.Context,
params *FetchObjectsParams,
) (FetchObjectsOutput, error) {
if err := params.Validate(); err != nil {
return FetchObjectsOutput{}, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
source := s.convertRepoSource(params.Source)
// sync repo content
err := s.git.FetchObjects(ctx, repoPath, source, params.ObjectSHAs)
if err != nil {
return FetchObjectsOutput{}, fmt.Errorf("failed to fetch git objects from source repo: %w", err)
}
return FetchObjectsOutput{}, nil
}
type GetRemoteDefaultBranchParams struct {
ReadParams
Source string
}
type GetRemoteDefaultBranchOutput struct {
BranchName string
}
func (s *Service) GetRemoteDefaultBranch(
ctx context.Context,
params *GetRemoteDefaultBranchParams,
) (*GetRemoteDefaultBranchOutput, error) {
source := s.convertRepoSource(params.Source)
branch, err := s.git.GetRemoteDefaultBranch(ctx, source)
if err != nil {
return nil, fmt.Errorf("failed to fetch git objects from source repo: %w", err)
}
return &GetRemoteDefaultBranchOutput{
BranchName: branch,
}, nil
}
// convertRepoSource converts the source in Git operations like SyncRepository or FetchObjects.
// If the source string contains no slash, we assume it's a GitUID and create a full path out of it.
// If it does contain a slash, we assume it's a URL and leave it intact.
func (s *Service) convertRepoSource(source string) string {
if strings.IndexByte(source, '/') >= 0 {
return source
}
return getFullPathForRepo(s.reposRoot, source)
}
type SyncRefsParams struct {
WriteParams
Source string
Refs []string
}
type SyncRefsOutput struct {
Refs []hook.ReferenceUpdate
}
func (s *Service) SyncRefs(
ctx context.Context,
params *SyncRefsParams,
) (*SyncRefsOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
source := s.convertRepoSource(params.Source)
refs := slices.Clone(params.Refs)
slices.Sort(refs)
refs = slices.Compact(refs)
refRemoteMap, err := s.git.ListRemoteReferences(ctx, repoPath, source, refs...)
if err != nil {
return nil, fmt.Errorf("failed to list remote refs: %w", err)
}
refLocalMap, err := s.git.ListLocalReferences(ctx, repoPath, refs...)
if err != nil {
return nil, fmt.Errorf("failed to list local refs: %w", err)
}
refsRemote := slices.Collect(maps.Keys(refRemoteMap))
slices.Sort(refsRemote)
if len(refsRemote) != len(refs) {
notFound := func(all, found []string) (notFound []string) {
var idxFound, idxAll int
for ; idxFound < len(found) && idxAll < len(all); idxAll++ {
if all[idxAll] == found[idxFound] {
idxFound++
continue
}
notFound = append(notFound, all[idxAll])
}
for ; idxAll < len(all); idxAll++ {
notFound = append(notFound, all[idxAll])
}
return
}(refs, refsRemote)
return nil, errors.InvalidArgumentf("Could not find remote references: %v", notFound)
}
refUpdater, err := hook.CreateRefUpdater(s.hookClientFactory, params.EnvVars, repoPath)
if err != nil {
return nil, fmt.Errorf("failed to create reference updater: %w", err)
}
refUpdates := make([]hook.ReferenceUpdate, 0, len(refs))
for _, ref := range refs {
oldSHA, ok := refLocalMap[ref]
if !ok {
oldSHA = sha.Nil
}
newSHA := refRemoteMap[ref]
if oldSHA == newSHA {
continue
}
refUpdates = append(refUpdates, hook.ReferenceUpdate{
Ref: ref,
Old: oldSHA,
New: newSHA,
})
}
if len(refUpdates) == 0 {
return &SyncRefsOutput{}, nil
}
err = sharedrepo.Run(ctx, refUpdater, s.sharedRepoRoot, repoPath, func(s *sharedrepo.SharedRepo) error {
objects := slices.Collect(maps.Values(refRemoteMap))
if err := s.FetchObjects(ctx, source, objects); err != nil {
return fmt.Errorf("failed to fetch objects: %w", err)
}
err = refUpdater.Init(ctx, refUpdates)
if err != nil {
return fmt.Errorf("failed to init values of references (%v): %w", refUpdates, err)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to sync references: %w", err)
}
return &SyncRefsOutput{
Refs: refUpdates,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/tag.go | git/tag.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"time"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/sha"
"github.com/harness/gitness/git/sharedrepo"
"github.com/rs/zerolog/log"
)
var (
listCommitTagsRefFields = []api.GitReferenceField{
api.GitReferenceFieldRefName,
api.GitReferenceFieldObjectType,
api.GitReferenceFieldObjectName,
}
listCommitTagsObjectTypeFilter = []api.GitObjectType{
api.GitObjectTypeCommit,
api.GitObjectTypeTag,
}
)
type TagSortOption int
const (
TagSortOptionDefault TagSortOption = iota
TagSortOptionName
TagSortOptionDate
)
type ListCommitTagsParams struct {
ReadParams
IncludeCommit bool
Query string
Sort TagSortOption
Order SortOrder
Page int32
PageSize int32
}
type ListCommitTagsOutput struct {
Tags []CommitTag
}
type CommitTag struct {
Name string
SHA sha.SHA
IsAnnotated bool
Title string
Message string
Tagger *Signature
SignedData *SignedData
Commit *Commit
}
type CreateCommitTagParams struct {
WriteParams
Name string
// Target is the commit (or points to the commit) the new tag will be pointing to.
Target string
// Message is the optional message the tag will be created with - if the message is empty
// the tag will be lightweight, otherwise it'll be annotated
Message string
// Tagger overwrites the git author used in case the tag is annotated
// (optional, default: actor)
Tagger *Identity
// TaggerDate overwrites the git author date used in case the tag is annotated
// (optional, default: current time on server)
TaggerDate *time.Time
}
func (p *CreateCommitTagParams) Validate() error {
if p == nil {
return ErrNoParamsProvided
}
if p.Name == "" {
return errors.New("tag name cannot be empty")
}
if p.Target == "" {
return errors.New("target cannot be empty")
}
return nil
}
type CreateCommitTagOutput struct {
CommitTag
}
type DeleteTagParams struct {
WriteParams
Name string
}
func (p DeleteTagParams) Validate() error {
if p.Name == "" {
return errors.New("tag name cannot be empty")
}
return nil
}
//nolint:gocognit
func (s *Service) ListCommitTags(
ctx context.Context,
params *ListCommitTagsParams,
) (*ListCommitTagsOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
// get all required information from git references
tags, err := s.listCommitTagsLoadReferenceData(ctx, repoPath, params)
if err != nil {
return nil, fmt.Errorf("ListCommitTags: failed to get git references: %w", err)
}
// get all tag and commit SHAs
annotatedTagSHAs := make([]sha.SHA, 0, len(tags))
commitSHAs := make([]sha.SHA, len(tags))
for i, tag := range tags {
// always set the commit sha (will be overwritten for annotated tags)
commitSHAs[i] = tag.SHA
if tag.IsAnnotated {
annotatedTagSHAs = append(annotatedTagSHAs, tag.SHA)
}
}
// populate annotation data for all annotated tags
if len(annotatedTagSHAs) > 0 {
var aTags []api.Tag
aTags, err = s.git.GetAnnotatedTags(ctx, repoPath, annotatedTagSHAs)
if err != nil {
return nil, fmt.Errorf("ListCommitTags: failed to get annotated tag: %w", err)
}
ai := 0 // index for annotated tags
ri := 0 // read index for all tags
wi := 0 // write index for all tags (as we might remove some non-commit tags)
for ; ri < len(tags); ri++ {
// always copy the current read element to the latest write position (doesn't mean it's kept)
tags[wi] = tags[ri]
commitSHAs[wi] = commitSHAs[ri]
// keep the tag as is if it's not annotated
if !tags[ri].IsAnnotated {
wi++
continue
}
// filter out annotated tags that don't point to commit objects (blobs, trees, nested tags, ...)
// we don't actually wanna write it, so keep write index
// TODO: Support proper pagination: https://harness.atlassian.net/browse/CODE-669
if aTags[ai].TargetType != api.GitObjectTypeCommit {
ai++
continue
}
// correct the commitSHA for the annotated tag (currently it is the tag sha, not the commit sha)
commitSHAs[wi] = aTags[ai].TargetSHA
tagger := mapSignature(aTags[ai].Tagger)
// update tag information with annotation details
// NOTE: we keep the name from the reference and ignore the annotated name (similar to github)
tags[wi].Message = aTags[ai].Message
tags[wi].Title = aTags[ai].Title
tags[wi].Tagger = &tagger
tags[wi].SignedData = (*SignedData)(aTags[ai].SignedData)
ai++
wi++
}
// truncate slices based on what was removed
tags = tags[:wi]
commitSHAs = commitSHAs[:wi]
}
// get commits if needed (single call for perf savings: 1s-4s vs 5s-20s)
if params.IncludeCommit {
gitCommits, err := s.git.GetCommits(ctx, repoPath, commitSHAs)
if err != nil {
return nil, fmt.Errorf("ListCommitTags: failed to get commits: %w", err)
}
for i := range gitCommits {
c, err := mapCommit(&gitCommits[i])
if err != nil {
return nil, fmt.Errorf("commit mapping error: %w", err)
}
tags[i].Commit = c
}
}
return &ListCommitTagsOutput{
Tags: tags,
}, nil
}
//nolint:gocognit
func (s *Service) CreateCommitTag(ctx context.Context, params *CreateCommitTagParams) (*CreateCommitTagOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
targetCommit, err := s.git.GetCommitFromRev(ctx, repoPath, params.Target)
if errors.IsNotFound(err) {
return nil, errors.NotFoundf("target '%s' doesn't exist", params.Target)
}
if err != nil {
return nil, fmt.Errorf("CreateCommitTag: failed to get commit id for target '%s': %w", params.Target, err)
}
tagName := params.Name
tagRef := api.GetReferenceFromTagName(tagName)
var tag *api.Tag
commitSHA, err := s.git.GetRef(ctx, repoPath, tagRef)
// TODO: Change GetRef to use errors.NotFound and then remove types.IsNotFoundError(err) below.
if err != nil && !errors.IsNotFound(err) {
return nil, fmt.Errorf("CreateCommitTag: failed to verify tag existence: %w", err)
}
if err == nil && !commitSHA.IsEmpty() {
return nil, errors.Conflictf("tag '%s' already exists", tagName)
}
// create tag request
tagger := params.Actor
if params.Tagger != nil {
tagger = *params.Tagger
}
taggerDate := time.Now().UTC()
if params.TaggerDate != nil {
taggerDate = *params.TaggerDate
}
createTagRequest := &api.CreateTagOptions{
Message: params.Message,
Tagger: api.Signature{
Identity: api.Identity{
Name: tagger.Name,
Email: tagger.Email,
},
When: taggerDate,
},
}
// ref updater
refUpdater, err := hook.CreateRefUpdater(s.hookClientFactory, params.EnvVars, repoPath)
if err != nil {
return nil, fmt.Errorf("failed to create ref updater to create the tag: %w", err)
}
// create the tag
err = sharedrepo.Run(ctx, refUpdater, s.sharedRepoRoot, repoPath, func(r *sharedrepo.SharedRepo) error {
if err := s.git.CreateTag(ctx, r.Directory(), tagName, targetCommit.SHA, createTagRequest); err != nil {
return fmt.Errorf("failed to create tag '%s': %w", tagName, err)
}
tag, err = s.git.GetAnnotatedTag(ctx, r.Directory(), tagName)
if err != nil {
return fmt.Errorf("failed to read annotated tag after creation: %w", err)
}
ref := hook.ReferenceUpdate{
Ref: tagRef,
Old: sha.Nil,
New: tag.Sha,
}
if err := refUpdater.Init(ctx, []hook.ReferenceUpdate{ref}); err != nil {
return fmt.Errorf("failed to init ref updater: %w", err)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("CreateCommitTag: failed to create tag in shared repository: %w", err)
}
// prepare response
var commitTag *CommitTag
if params.Message != "" {
tag, err = s.git.GetAnnotatedTag(ctx, repoPath, params.Name)
if err != nil {
return nil, fmt.Errorf("failed to read annotated tag after creation: %w", err)
}
commitTag = mapAnnotatedTag(tag)
} else {
commitTag = &CommitTag{
Name: params.Name,
IsAnnotated: false,
SHA: targetCommit.SHA,
}
}
c, err := mapCommit(targetCommit)
if err != nil {
return nil, err
}
commitTag.Commit = c
return &CreateCommitTagOutput{CommitTag: *commitTag}, nil
}
func (s *Service) DeleteTag(ctx context.Context, params *DeleteTagParams) error {
if err := params.Validate(); err != nil {
return err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
refUpdater, err := hook.CreateRefUpdater(s.hookClientFactory, params.EnvVars, repoPath)
if err != nil {
return fmt.Errorf("failed to create ref updater to delete the tag: %w", err)
}
tagRef := api.GetReferenceFromTagName(params.Name)
err = refUpdater.DoOne(ctx, tagRef, sha.None, sha.Nil) // delete whatever is there
if errors.IsNotFound(err) {
return errors.NotFoundf("tag %q does not exist", params.Name)
}
if err != nil {
return fmt.Errorf("failed to init ref updater: %w", err)
}
return nil
}
func (s *Service) listCommitTagsLoadReferenceData(
ctx context.Context,
repoPath string,
params *ListCommitTagsParams,
) ([]CommitTag, error) {
// TODO: can we be smarter with slice allocation
tags := make([]CommitTag, 0, 16)
handler := listCommitTagsWalkReferencesHandler(&tags)
instructor, _, err := wrapInstructorWithOptionalPagination(
newInstructorWithObjectTypeFilter(listCommitTagsObjectTypeFilter),
params.Page,
params.PageSize,
)
if err != nil {
return nil, errors.InvalidArgumentf("invalid pagination details: %v", err)
}
opts := &api.WalkReferencesOptions{
Patterns: createReferenceWalkPatternsFromQuery(gitReferenceNamePrefixTag, params.Query),
Sort: mapListCommitTagsSortOption(params.Sort),
Order: mapToSortOrder(params.Order),
Fields: listCommitTagsRefFields,
Instructor: instructor,
// we do post-filtering, so we can't restrict the git output ...
MaxWalkDistance: 0,
}
err = s.git.WalkReferences(ctx, repoPath, handler, opts)
if err != nil {
return nil, fmt.Errorf("failed to walk tag references: %w", err)
}
log.Ctx(ctx).Trace().Msgf("git api returned %d tags", len(tags))
return tags, nil
}
func listCommitTagsWalkReferencesHandler(tags *[]CommitTag) api.WalkReferencesHandler {
return func(e api.WalkReferencesEntry) error {
fullRefName, ok := e[api.GitReferenceFieldRefName]
if !ok {
return fmt.Errorf("entry missing reference name")
}
objectSHA, ok := e[api.GitReferenceFieldObjectName]
if !ok {
return fmt.Errorf("entry missing object sha")
}
objectTypeRaw, ok := e[api.GitReferenceFieldObjectType]
if !ok {
return fmt.Errorf("entry missing object type")
}
tag := CommitTag{
Name: fullRefName[len(gitReferenceNamePrefixTag):],
SHA: sha.Must(objectSHA),
IsAnnotated: objectTypeRaw == string(api.GitObjectTypeTag),
}
// TODO: refactor to not use slice pointers?
*tags = append(*tags, tag)
return nil
}
}
func newInstructorWithObjectTypeFilter(filter []api.GitObjectType) api.WalkReferencesInstructor {
return func(wre api.WalkReferencesEntry) (api.WalkInstruction, error) {
v, ok := wre[api.GitReferenceFieldObjectType]
if !ok {
return api.WalkInstructionStop, fmt.Errorf("ref field for object type is missing")
}
// only handle if any of the filters match
for _, field := range filter {
if v == string(field) {
return api.WalkInstructionHandle, nil
}
}
// by default skip
return api.WalkInstructionSkip, nil
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/diff.go | git/diff.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"bufio"
"context"
"fmt"
"io"
"sync"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/diff"
"github.com/harness/gitness/git/enum"
"github.com/harness/gitness/git/parser"
"github.com/harness/gitness/git/sha"
"golang.org/x/sync/errgroup"
)
type DiffParams struct {
ReadParams
BaseRef string
HeadRef string
MergeBase bool
IncludePatch bool
IgnoreWhitespace bool
}
func (p DiffParams) Validate() error {
if err := p.ReadParams.Validate(); err != nil {
return err
}
if p.HeadRef == "" {
return errors.InvalidArgument("head ref cannot be empty")
}
return nil
}
func (s *Service) RawDiff(
ctx context.Context,
out io.Writer,
params *DiffParams,
files ...api.FileDiffRequest,
) error {
return s.rawDiff(ctx, out, params, files...)
}
func (s *Service) rawDiff(ctx context.Context, w io.Writer, params *DiffParams, files ...api.FileDiffRequest) error {
if err := params.Validate(); err != nil {
return err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
err := s.git.RawDiff(ctx,
w,
repoPath,
params.BaseRef,
params.HeadRef,
params.MergeBase,
params.IgnoreWhitespace,
params.AlternateObjectDirs,
files...,
)
if err != nil {
return err
}
return nil
}
func (s *Service) CommitDiff(ctx context.Context, params *GetCommitParams, out io.Writer) error {
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
err := s.git.CommitDiff(
ctx,
repoPath,
params.Revision,
params.IgnoreWhitespace,
out,
)
if err != nil {
return err
}
return nil
}
type DiffShortStatOutput struct {
Files int
Additions int
Deletions int
}
// DiffShortStat returns files changed, additions and deletions metadata.
func (s *Service) DiffShortStat(ctx context.Context, params *DiffParams) (DiffShortStatOutput, error) {
if err := params.Validate(); err != nil {
return DiffShortStatOutput{}, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
stat, err := s.git.DiffShortStat(ctx,
repoPath,
params.BaseRef,
params.HeadRef,
params.MergeBase,
params.IgnoreWhitespace,
)
if err != nil {
return DiffShortStatOutput{}, err
}
return DiffShortStatOutput{
Files: stat.Files,
Additions: stat.Additions,
Deletions: stat.Deletions,
}, nil
}
type DiffStatsOutput struct {
Commits int
FilesChanged int
Additions int
Deletions int
}
func (s *Service) DiffStats(ctx context.Context, params *DiffParams) (DiffStatsOutput, error) {
// declare variables which will be used in go routines,
// no need for atomic operations because writing and reading variable
// doesn't happen at the same time
var (
totalCommits int
totalFiles int
additions int
deletions int
)
errGroup, groupCtx := errgroup.WithContext(ctx)
errGroup.Go(func() error {
// read total commits
options := &GetCommitDivergencesParams{
ReadParams: params.ReadParams,
Requests: []CommitDivergenceRequest{
{
From: params.HeadRef,
To: params.BaseRef,
},
},
}
rpcOutput, err := s.GetCommitDivergences(groupCtx, options)
if err != nil {
return err
}
if len(rpcOutput.Divergences) > 0 {
totalCommits = int(rpcOutput.Divergences[0].Ahead)
}
return nil
})
errGroup.Go(func() error {
// read short stat
stat, err := s.DiffShortStat(groupCtx, &DiffParams{
ReadParams: params.ReadParams,
BaseRef: params.BaseRef,
HeadRef: params.HeadRef,
MergeBase: true, // must be true, because commitDivergences use triple dot notation
IgnoreWhitespace: params.IgnoreWhitespace,
})
if err != nil {
return err
}
totalFiles = stat.Files
additions = stat.Additions
deletions = stat.Deletions
return nil
})
err := errGroup.Wait()
if err != nil {
return DiffStatsOutput{}, err
}
return DiffStatsOutput{
Commits: totalCommits,
FilesChanged: totalFiles,
Additions: additions,
Deletions: deletions,
}, nil
}
type GetDiffHunkHeadersParams struct {
ReadParams
SourceCommitSHA string
TargetCommitSHA string
}
type DiffFileHeader struct {
OldName string
NewName string
Extensions map[string]string
}
type DiffFileHunkHeaders struct {
FileHeader DiffFileHeader
HunkHeaders []HunkHeader
}
type GetDiffHunkHeadersOutput struct {
Files []DiffFileHunkHeaders
}
func (s *Service) GetDiffHunkHeaders(
ctx context.Context,
params GetDiffHunkHeadersParams,
) (GetDiffHunkHeadersOutput, error) {
if params.SourceCommitSHA == params.TargetCommitSHA {
return GetDiffHunkHeadersOutput{}, nil
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
hunkHeaders, err := s.git.GetDiffHunkHeaders(
ctx,
repoPath,
params.TargetCommitSHA,
params.SourceCommitSHA,
)
if err != nil {
return GetDiffHunkHeadersOutput{}, err
}
files := make([]DiffFileHunkHeaders, len(hunkHeaders))
for i, file := range hunkHeaders {
headers := make([]HunkHeader, len(file.HunksHeaders))
for j := range file.HunksHeaders {
headers[j] = mapHunkHeader(&file.HunksHeaders[j])
}
files[i] = DiffFileHunkHeaders{
FileHeader: mapDiffFileHeader(&hunkHeaders[i].FileHeader),
HunkHeaders: headers,
}
}
return GetDiffHunkHeadersOutput{
Files: files,
}, nil
}
type DiffCutOutput struct {
Header HunkHeader
LinesHeader string
Lines []string
MergeBaseSHA sha.SHA
}
type DiffCutParams struct {
ReadParams
SourceCommitSHA string
TargetCommitSHA string
Path string
LineStart int
LineStartNew bool
LineEnd int
LineEndNew bool
LineLimit int
IgnoreWhitespace bool
}
// DiffCut extracts diff snippet from a git diff hunk.
// The snippet is from the diff between the specified commit SHAs.
func (s *Service) DiffCut(ctx context.Context, params *DiffCutParams) (DiffCutOutput, error) {
if params.SourceCommitSHA == params.TargetCommitSHA {
return DiffCutOutput{}, errors.InvalidArgument("source and target SHA cannot be the same")
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
mergeBaseSHA, _, err := s.git.GetMergeBase(ctx, repoPath, "",
params.TargetCommitSHA, params.SourceCommitSHA, false)
if err != nil {
return DiffCutOutput{}, fmt.Errorf("failed to find merge base: %w", err)
}
header, linesHunk, err := s.git.DiffCut(
ctx,
repoPath,
params.TargetCommitSHA,
params.SourceCommitSHA,
params.Path,
params.IgnoreWhitespace,
parser.DiffCutParams{
LineStart: params.LineStart,
LineStartNew: params.LineStartNew,
LineEnd: params.LineEnd,
LineEndNew: params.LineEndNew,
BeforeLines: 2,
AfterLines: 2,
LineLimit: params.LineLimit,
},
)
if err != nil {
return DiffCutOutput{}, fmt.Errorf("DiffCut: failed to get diff hunk: %w", err)
}
hunkHeader := HunkHeader{
OldLine: header.OldLine,
OldSpan: header.OldSpan,
NewLine: header.NewLine,
NewSpan: header.NewSpan,
Text: header.Text,
}
return DiffCutOutput{
Header: hunkHeader,
LinesHeader: linesHunk.HunkHeader.String(),
Lines: linesHunk.Lines,
MergeBaseSHA: mergeBaseSHA,
}, nil
}
type FileDiff struct {
SHA string `json:"sha"`
OldSHA string `json:"old_sha,omitempty"`
Path string `json:"path"`
OldPath string `json:"old_path,omitempty"`
Status enum.FileDiffStatus `json:"status"`
Additions int64 `json:"additions"`
Deletions int64 `json:"deletions"`
Changes int64 `json:"changes"`
Patch []byte `json:"patch,omitempty"`
IsBinary bool `json:"is_binary"`
IsSubmodule bool `json:"is_submodule"`
}
func parseFileDiffStatus(ftype diff.FileType) enum.FileDiffStatus {
switch ftype {
case diff.FileAdd:
return enum.FileDiffStatusAdded
case diff.FileDelete:
return enum.FileDiffStatusDeleted
case diff.FileChange:
return enum.FileDiffStatusModified
case diff.FileRename:
return enum.FileDiffStatusRenamed
default:
return enum.FileDiffStatusUndefined
}
}
//nolint:gocognit
func (s *Service) Diff(
ctx context.Context,
params *DiffParams,
files ...api.FileDiffRequest,
) (<-chan *FileDiff, <-chan error) {
wg := sync.WaitGroup{}
ch := make(chan *FileDiff)
cherr := make(chan error, 1)
pr, pw := io.Pipe()
wg.Add(1)
go func() {
defer wg.Done()
defer pw.Close()
if err := params.Validate(); err != nil {
cherr <- err
return
}
err := s.rawDiff(ctx, pw, params, files...)
if err != nil {
cherr <- err
return
}
}()
wg.Add(1)
go func() {
defer wg.Done()
defer pr.Close()
parser := diff.Parser{
Reader: bufio.NewReader(pr),
IncludePatch: params.IncludePatch,
}
err := parser.Parse(func(f *diff.File) error {
ch <- &FileDiff{
SHA: f.SHA,
OldSHA: f.OldSHA,
Path: f.Path,
OldPath: f.OldPath,
Status: parseFileDiffStatus(f.Type),
Additions: int64(f.NumAdditions()),
Deletions: int64(f.NumDeletions()),
Changes: int64(f.NumChanges()),
Patch: f.Patch.Bytes(),
IsBinary: f.IsBinary,
IsSubmodule: f.IsSubmodule,
}
return nil
})
if err != nil {
cherr <- err
return
}
}()
go func() {
wg.Wait()
defer close(ch)
defer close(cherr)
}()
return ch, cherr
}
type DiffFileNamesOutput struct {
Files []string
}
func (s *Service) DiffFileNames(ctx context.Context, params *DiffParams) (DiffFileNamesOutput, error) {
if err := params.Validate(); err != nil {
return DiffFileNamesOutput{}, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
fileNames, err := s.git.DiffFileName(
ctx,
repoPath,
params.BaseRef,
params.HeadRef,
params.MergeBase,
params.IgnoreWhitespace,
)
if err != nil {
return DiffFileNamesOutput{}, fmt.Errorf("failed to get diff file data between '%s' and '%s': %w",
params.BaseRef, params.HeadRef, err)
}
return DiffFileNamesOutput{
Files: fileNames,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/signed_data.go | git/signed_data.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
// SignedData represents a git signature part.
type SignedData struct {
Type string
Signature []byte
SignedContent []byte
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/match_files.go | git/match_files.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"github.com/harness/gitness/git/api"
)
type MatchFilesParams struct {
ReadParams
Ref string
DirPath string
Pattern string
MaxSize int
}
type MatchFilesOutput struct {
Files []api.FileContent
}
func (s *Service) MatchFiles(ctx context.Context,
params *MatchFilesParams,
) (*MatchFilesOutput, error) {
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
matchedFiles, err := s.git.MatchFiles(ctx, repoPath,
params.Ref, params.DirPath, params.Pattern, params.MaxSize)
if err != nil {
return nil, fmt.Errorf("MatchFiles: failed to open repo: %w", err)
}
return &MatchFilesOutput{
Files: matchedFiles,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/env.go | git/env.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
)
const (
EnvActorName = "GITNESS_HOOK_ACTOR_NAME"
EnvActorEmail = "GITNESS_HOOK_ACTOR_EMAIL" //#nosec
EnvRepoUID = "GITNESS_HOOK_REPO_UID"
EnvRequestID = "GITNESS_HOOK_REQUEST_ID"
)
// ASSUMPTION: writeRequst and writeRequst.Actor is never nil.
func CreateEnvironmentForPush(ctx context.Context, writeRequest WriteParams) []string {
// don't send existing environment variables (os.Environ()), only send what's explicitly necessary.
// Otherwise we create implicit dependencies that are easy to break.
environ := []string{
// request id to use for hooks
EnvRequestID + "=" + RequestIDFrom(ctx),
// repo related info
EnvRepoUID + "=" + writeRequest.RepoUID,
// actor related info
EnvActorName + "=" + writeRequest.Actor.Name,
EnvActorEmail + "=" + writeRequest.Actor.Email,
}
// add all environment variables coming from client request
for key, value := range writeRequest.EnvVars {
environ = append(environ, fmt.Sprintf("%s=%s", key, value))
}
return environ
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/context.go | git/context.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import "context"
const (
RequestIDNone string = "git_none"
)
// requestIDKey is context key for storing and retrieving the request ID to and from a context.
type requestIDKey struct{}
// RequestIDFrom retrieves the request id from the context.
// If no request id exists, RequestIDNone is returned.
func RequestIDFrom(ctx context.Context) string {
if v, ok := ctx.Value(requestIDKey{}).(string); ok {
return v
}
return RequestIDNone
}
// WithRequestID returns a copy of parent in which the request id value is set.
// This can be used by external entities to pass request IDs.
func WithRequestID(parent context.Context, v string) context.Context {
return context.WithValue(parent, requestIDKey{}, v)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/branch.go | git/branch.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"strings"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/check"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/sha"
"github.com/rs/zerolog/log"
)
type BranchSortOption int
const (
BranchSortOptionDefault BranchSortOption = iota
BranchSortOptionName
BranchSortOptionDate
)
var listBranchesRefFields = []api.GitReferenceField{
api.GitReferenceFieldRefName,
api.GitReferenceFieldObjectName,
}
type Branch struct {
Name string
SHA sha.SHA
Commit *Commit
}
type CreateBranchParams struct {
WriteParams
// BranchName is the name of the branch
BranchName string
// Target is a git reference (branch / tag / commit SHA)
Target string
}
type CreateBranchOutput struct {
Branch Branch
}
type GetBranchParams struct {
ReadParams
// BranchName is the name of the branch
BranchName string
}
type GetBranchOutput struct {
Branch Branch
}
type DeleteBranchParams struct {
WriteParams
// BranchName is the name of the branch
BranchName string
SHA string
}
type ListBranchesParams struct {
ReadParams
IncludeCommit bool
Query string
Sort BranchSortOption
Order SortOrder
Page int32
PageSize int32
}
type ListBranchesOutput struct {
Branches []Branch
}
func (s *Service) CreateBranch(ctx context.Context, params *CreateBranchParams) (*CreateBranchOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
if err := check.BranchName(params.BranchName); err != nil {
return nil, errors.InvalidArgument(err.Error())
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
targetCommit, err := s.git.GetCommitFromRev(ctx, repoPath, strings.TrimSpace(params.Target))
if err != nil {
return nil, fmt.Errorf("failed to get target commit: %w", err)
}
refUpdater, err := hook.CreateRefUpdater(s.hookClientFactory, params.EnvVars, repoPath)
if err != nil {
return nil, fmt.Errorf("failed to create ref updater to create the branch: %w", err)
}
branchRef := api.GetReferenceFromBranchName(params.BranchName)
err = refUpdater.DoOne(ctx, branchRef, sha.Nil, targetCommit.SHA)
if errors.IsConflict(err) {
return nil, errors.Conflictf("branch %q already exists", params.BranchName)
}
if err != nil {
return nil, fmt.Errorf("failed to create branch reference: %w", err)
}
commit, err := mapCommit(targetCommit)
if err != nil {
return nil, fmt.Errorf("failed to map git commit: %w", err)
}
return &CreateBranchOutput{
Branch: Branch{
Name: params.BranchName,
SHA: commit.SHA,
Commit: commit,
},
}, nil
}
func (s *Service) GetBranch(ctx context.Context, params *GetBranchParams) (*GetBranchOutput, error) {
if params == nil {
return nil, ErrNoParamsProvided
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
sanitizedBranchName := strings.TrimPrefix(params.BranchName, gitReferenceNamePrefixBranch)
gitBranch, err := s.git.GetBranch(ctx, repoPath, sanitizedBranchName)
if err != nil {
return nil, err
}
branch, err := mapBranch(gitBranch)
if err != nil {
return nil, fmt.Errorf("failed to map rpc branch %v: %w", gitBranch.Name, err)
}
return &GetBranchOutput{
Branch: *branch,
}, nil
}
func (s *Service) DeleteBranch(ctx context.Context, params *DeleteBranchParams) error {
if params == nil {
return ErrNoParamsProvided
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
commitSha, _ := sha.NewOrEmpty(params.SHA)
refUpdater, err := hook.CreateRefUpdater(s.hookClientFactory, params.EnvVars, repoPath)
if err != nil {
return fmt.Errorf("failed to create ref updater to create the branch: %w", err)
}
branchRef := api.GetReferenceFromBranchName(params.BranchName)
err = refUpdater.DoOne(ctx, branchRef, commitSha, sha.Nil)
if errors.IsNotFound(err) {
return errors.NotFoundf("branch %q does not exist", params.BranchName)
}
if err != nil {
return fmt.Errorf("failed to delete branch reference: %w", err)
}
return nil
}
func (s *Service) ListBranches(ctx context.Context, params *ListBranchesParams) (*ListBranchesOutput, error) {
if params == nil {
return nil, ErrNoParamsProvided
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
gitBranches, err := s.listBranchesLoadReferenceData(ctx, repoPath, api.BranchFilter{
IncludeCommit: params.IncludeCommit,
Query: params.Query,
Sort: mapBranchesSortOption(params.Sort),
Order: mapToSortOrder(params.Order),
Page: params.Page,
PageSize: params.PageSize,
})
if err != nil {
return nil, err
}
// get commits if needed (single call for perf savings: 1s-4s vs 5s-20s)
if params.IncludeCommit {
commitSHAs := make([]sha.SHA, len(gitBranches))
for i := range gitBranches {
commitSHAs[i] = gitBranches[i].SHA
}
var gitCommits []api.Commit
gitCommits, err = s.git.GetCommits(ctx, repoPath, commitSHAs)
if err != nil {
return nil, fmt.Errorf("failed to get commit: %w", err)
}
for i := range gitCommits {
gitBranches[i].Commit = &gitCommits[i]
}
}
branches := make([]Branch, len(gitBranches))
for i, branch := range gitBranches {
b, err := mapBranch(branch)
if err != nil {
return nil, err
}
branches[i] = *b
}
return &ListBranchesOutput{
Branches: branches,
}, nil
}
func (s *Service) listBranchesLoadReferenceData(
ctx context.Context,
repoPath string,
filter api.BranchFilter,
) ([]*api.Branch, error) {
// TODO: can we be smarter with slice allocation
branches := make([]*api.Branch, 0, 16)
handler := listBranchesWalkReferencesHandler(&branches)
instructor, endsAfter, err := wrapInstructorWithOptionalPagination(
api.DefaultInstructor, // branches only have one target type, default instructor is enough
filter.Page,
filter.PageSize,
)
if err != nil {
return nil, errors.InvalidArgumentf("invalid pagination details: %v", err)
}
opts := &api.WalkReferencesOptions{
Patterns: createReferenceWalkPatternsFromQuery(gitReferenceNamePrefixBranch, filter.Query),
Sort: filter.Sort,
Order: filter.Order,
Fields: listBranchesRefFields,
Instructor: instructor,
// we don't do any post-filtering, restrict git to only return as many elements as pagination needs.
MaxWalkDistance: endsAfter,
}
err = s.git.WalkReferences(ctx, repoPath, handler, opts)
if err != nil {
return nil, fmt.Errorf("failed to walk branch references: %w", err)
}
log.Ctx(ctx).Trace().Msgf("git api returned %d branches", len(branches))
return branches, nil
}
func listBranchesWalkReferencesHandler(
branches *[]*api.Branch,
) api.WalkReferencesHandler {
return func(e api.WalkReferencesEntry) error {
fullRefName, ok := e[api.GitReferenceFieldRefName]
if !ok {
return fmt.Errorf("entry missing reference name")
}
objectSHA, ok := e[api.GitReferenceFieldObjectName]
if !ok {
return fmt.Errorf("entry missing object sha")
}
branch := &api.Branch{
Name: fullRefName[len(gitReferenceNamePrefixBranch):],
SHA: sha.Must(objectSHA),
}
// TODO: refactor to not use slice pointers?
*branches = append(*branches, branch)
return nil
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/upload.go | git/upload.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"bytes"
"context"
"fmt"
"path/filepath"
"time"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/rs/zerolog/log"
)
const (
// TODO: this should be configurable
FileTransferChunkSize = 1024
)
type File struct {
Path string
Content []byte
}
// TODO: this should be taken as a struct input defined in proto.
func (s *Service) addFilesAndPush(
ctx context.Context,
repoPath string,
filePaths []string,
branch string,
env []string,
author *Identity,
authorDate time.Time,
committer *Identity,
committerDate time.Time,
remote string,
message string,
) error {
if author == nil || committer == nil {
return errors.InvalidArgument("both author and committer have to be provided")
}
err := s.git.AddFiles(ctx, repoPath, false, filePaths...)
if err != nil {
return fmt.Errorf("failed to add files: %w", err)
}
err = s.git.Commit(ctx, repoPath, api.CommitChangesOptions{
Committer: api.Signature{
Identity: api.Identity{
Name: committer.Name,
Email: committer.Email,
},
When: committerDate,
},
Author: api.Signature{
Identity: api.Identity{
Name: author.Name,
Email: author.Email,
},
When: authorDate,
},
Message: message,
})
if err != nil {
return fmt.Errorf("failed to commit files: %w", err)
}
err = s.git.Push(ctx, repoPath, api.PushOptions{
// TODO: Don't hard-code
Remote: remote,
Branch: branch,
Force: false,
Env: env,
Timeout: 0,
})
if err != nil {
return fmt.Errorf("failed to push files: %w", err)
}
return nil
}
func (s *Service) handleFileUploadIfAvailable(
ctx context.Context,
basePath string,
file File,
) (string, error) {
log := log.Ctx(ctx)
fullPath := filepath.Join(basePath, file.Path)
log.Info().Msgf("saving file at path %s", fullPath)
_, err := s.store.Save(fullPath, bytes.NewReader(file.Content))
if err != nil {
return "", errors.Internalf(err, "cannot save file to the store: %s", fullPath)
}
return fullPath, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/push_remote.go | git/push_remote.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
)
type PushRemoteParams struct {
ReadParams
RemoteURL string
}
func (p *PushRemoteParams) Validate() error {
if p == nil {
return ErrNoParamsProvided
}
if err := p.ReadParams.Validate(); err != nil {
return err
}
if p.RemoteURL == "" {
return errors.InvalidArgument("remote url cannot be empty")
}
return nil
}
func (s *Service) PushRemote(ctx context.Context, params *PushRemoteParams) error {
if err := params.Validate(); err != nil {
return err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
isEmpty, err := s.git.HasBranches(ctx, repoPath)
if err != nil {
return errors.Internal(err, "push to repo failed")
}
if isEmpty {
return errors.InvalidArgument("cannot push empty repo")
}
err = s.git.Push(ctx, repoPath, api.PushOptions{
Remote: params.RemoteURL,
Force: false,
Env: nil,
Mirror: true,
})
if err != nil {
return fmt.Errorf("PushRemote: failed to push to remote repository: %w", err)
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/mapping.go | git/mapping.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"fmt"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/parser"
)
func mapBranch(b *api.Branch) (*Branch, error) {
if b == nil {
return nil, fmt.Errorf("rpc branch is nil")
}
var commit *Commit
if b.Commit != nil {
var err error
commit, err = mapCommit(b.Commit)
if err != nil {
return nil, err
}
}
return &Branch{
Name: b.Name,
SHA: b.SHA,
Commit: commit,
}, nil
}
func mapCommit(c *api.Commit) (*Commit, error) {
if c == nil {
return nil, fmt.Errorf("rpc commit is nil")
}
return &Commit{
SHA: c.SHA,
TreeSHA: c.TreeSHA,
ParentSHAs: c.ParentSHAs,
Title: c.Title,
Message: c.Message,
Author: mapSignature(c.Author),
Committer: mapSignature(c.Committer),
SignedData: (*SignedData)(c.SignedData),
FileStats: mapFileStats(c.FileStats),
}, nil
}
func mapFileStats(typeStats []api.CommitFileStats) []CommitFileStats {
var stats = make([]CommitFileStats, len(typeStats))
for i, tStat := range typeStats {
stats[i] = CommitFileStats{
Status: tStat.ChangeType,
Path: tStat.Path,
OldPath: tStat.OldPath,
Insertions: tStat.Insertions,
Deletions: tStat.Deletions,
}
}
return stats
}
func mapSignature(s api.Signature) Signature {
return Signature{
Identity: Identity(s.Identity),
When: s.When,
}
}
func mapBranchesSortOption(o BranchSortOption) api.GitReferenceField {
switch o {
case BranchSortOptionName:
return api.GitReferenceFieldObjectName
case BranchSortOptionDate:
return api.GitReferenceFieldCreatorDate
case BranchSortOptionDefault:
fallthrough
default:
// no need to error out - just use default for sorting
return ""
}
}
func mapAnnotatedTag(tag *api.Tag) *CommitTag {
tagger := mapSignature(tag.Tagger)
return &CommitTag{
Name: tag.Name,
SHA: tag.Sha,
Title: tag.Title,
Message: tag.Message,
Tagger: &tagger,
IsAnnotated: true,
SignedData: (*SignedData)(tag.SignedData),
Commit: nil,
}
}
func mapListCommitTagsSortOption(s TagSortOption) api.GitReferenceField {
switch s {
case TagSortOptionDate:
return api.GitReferenceFieldCreatorDate
case TagSortOptionName:
return api.GitReferenceFieldRefName
case TagSortOptionDefault:
return api.GitReferenceFieldRefName
default:
// no need to error out - just use default for sorting
return api.GitReferenceFieldRefName
}
}
func mapTreeNode(n *api.TreeNode) (TreeNode, error) {
if n == nil {
return TreeNode{}, fmt.Errorf("rpc tree node is nil")
}
nodeType, err := mapTreeNodeType(n.NodeType)
if err != nil {
return TreeNode{}, err
}
mode, err := mapTreeNodeMode(n.Mode)
if err != nil {
return TreeNode{}, err
}
return TreeNode{
Type: nodeType,
Mode: mode,
SHA: n.SHA.String(),
Name: n.Name,
Path: n.Path,
}, nil
}
func mapTreeNodeType(t api.TreeNodeType) (TreeNodeType, error) {
switch t {
case api.TreeNodeTypeBlob:
return TreeNodeTypeBlob, nil
case api.TreeNodeTypeCommit:
return TreeNodeTypeCommit, nil
case api.TreeNodeTypeTree:
return TreeNodeTypeTree, nil
default:
return TreeNodeTypeBlob, fmt.Errorf("unknown rpc tree node type: %d", t)
}
}
func mapTreeNodeMode(m api.TreeNodeMode) (TreeNodeMode, error) {
switch m {
case api.TreeNodeModeFile:
return TreeNodeModeFile, nil
case api.TreeNodeModeExec:
return TreeNodeModeExec, nil
case api.TreeNodeModeSymlink:
return TreeNodeModeSymlink, nil
case api.TreeNodeModeCommit:
return TreeNodeModeCommit, nil
case api.TreeNodeModeTree:
return TreeNodeModeTree, nil
default:
return TreeNodeModeFile, fmt.Errorf("unknown rpc tree node mode: %d", m)
}
}
func mapRenameDetails(c []api.PathRenameDetails) []*RenameDetails {
renameDetailsList := make([]*RenameDetails, len(c))
for i, detail := range c {
renameDetailsList[i] = &RenameDetails{
OldPath: detail.OldPath,
NewPath: detail.Path,
CommitShaBefore: detail.CommitSHABefore,
CommitShaAfter: detail.CommitSHAAfter,
}
}
return renameDetailsList
}
func mapToSortOrder(o SortOrder) api.SortOrder {
switch o {
case SortOrderAsc:
return api.SortOrderAsc
case SortOrderDesc:
return api.SortOrderDesc
case SortOrderDefault:
return api.SortOrderDefault
default:
// no need to error out - just use default for sorting
return api.SortOrderDefault
}
}
func mapHunkHeader(h *parser.HunkHeader) HunkHeader {
return HunkHeader{
OldLine: h.OldLine,
OldSpan: h.OldSpan,
NewLine: h.NewLine,
NewSpan: h.NewSpan,
Text: h.Text,
}
}
func mapDiffFileHeader(h *parser.DiffFileHeader) DiffFileHeader {
return DiffFileHeader{
OldName: h.OldFileName,
NewName: h.NewFileName,
Extensions: h.Extensions,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/optimize.go | git/optimize.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/gotidy/ptr"
)
const (
// FullRepackCooldownPeriod is the cooldown period that needs to pass since the last full
// repack before we consider doing another full repack.
FullRepackCooldownPeriod = 5 * 24 * time.Hour
// LooseObjectLimit is the limit of loose objects we accept both when doing incremental
// repacks and when pruning objects.
LooseObjectLimit = 1024
)
type OptimizeRepoStrategy int
const (
OptimizeRepoStrategyGC OptimizeRepoStrategy = 0
OptimizeRepoStrategyHeuristic OptimizeRepoStrategy = 1
OptimizeRepoStrategyFull OptimizeRepoStrategy = 2
)
func (s OptimizeRepoStrategy) Validate() error {
switch s {
case OptimizeRepoStrategyGC, OptimizeRepoStrategyHeuristic, OptimizeRepoStrategyFull:
return nil
default:
return fmt.Errorf("invalid optimization strategy: %d", s)
}
}
type OptimizeRepositoryParams struct {
ReadParams
Strategy OptimizeRepoStrategy
GCArgs map[string]string // additional arguments for git gc command
}
func (p OptimizeRepositoryParams) Validate() error {
if err := p.ReadParams.Validate(); err != nil {
return err
}
if err := p.Strategy.Validate(); err != nil {
return err
}
return nil
}
func parseGCArgs(args map[string]string) api.GCParams {
var params api.GCParams
for arg, value := range args {
argLower := strings.ToLower(arg)
switch argLower {
case "aggressive":
if boolVal, err := strconv.ParseBool(value); err == nil {
params.Aggressive = boolVal
}
case "auto":
if boolVal, err := strconv.ParseBool(value); err == nil {
params.Auto = boolVal
}
case "cruft":
if boolVal, err := strconv.ParseBool(value); err == nil {
params.Cruft = &boolVal
}
case "max-cruft-size":
if intVal, err := strconv.ParseUint(value, 10, 64); err == nil {
params.MaxCruftSize = intVal
}
case "prune":
// Try parsing as time
if t, err := time.Parse(api.RFC2822DateFormat, value); err == nil {
params.Prune = t
} else if boolVal, err := strconv.ParseBool(value); err == nil {
params.Prune = &boolVal
} else {
params.Prune = value
}
case "keep-largest-pack":
if boolVal, err := strconv.ParseBool(value); err == nil {
params.KeepLargestPack = boolVal
}
}
}
return params
}
func (s *Service) OptimizeRepository(
ctx context.Context,
params OptimizeRepositoryParams,
) error {
if err := params.Validate(); err != nil {
return err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
repoInfo, err := api.LoadRepositoryInfo(repoPath)
if err != nil {
return fmt.Errorf("loading repository info: %w", err)
}
var optimizationStrategy OptimizationStrategy
switch params.Strategy {
case OptimizeRepoStrategyGC:
err := s.git.GC(ctx, repoPath, parseGCArgs(params.GCArgs))
if err != nil {
return fmt.Errorf("GC repository error: %w", err)
}
return nil
case OptimizeRepoStrategyHeuristic:
optimizationStrategy = NewHeuristicalOptimizationStrategy(repoInfo)
case OptimizeRepoStrategyFull:
optimizationStrategy = NewFullOptimizationStrategy(repoInfo)
default:
return errors.InvalidArgument("invalid strategy provided")
}
repackNeeded, repackParams := optimizationStrategy.ShouldRepackObjects(ctx)
if repackNeeded {
err := s.repackObjects(ctx, repoPath, repackParams)
if err != nil {
return fmt.Errorf("optimizing (repacking) repository failed: %w", err)
}
}
pruneNeeded, pruneParams := optimizationStrategy.ShouldPruneObjects(ctx)
if pruneNeeded {
err := s.git.PruneObjects(ctx, repoPath, api.PruneObjectsParams{
ExpireBefore: pruneParams.ExpireBefore,
})
if err != nil {
return fmt.Errorf("pruning objects failed: %w", err)
}
}
packRefsNeeded := optimizationStrategy.ShouldRepackReferences(ctx)
if packRefsNeeded {
err := s.git.PackRefs(ctx, repoPath, api.PackRefsParams{
All: true,
})
if err != nil {
return fmt.Errorf("packing references failed: %w", err)
}
}
writeGraphNeeded, p, err := optimizationStrategy.ShouldWriteCommitGraph(ctx)
if err != nil {
return err
}
if writeGraphNeeded {
cgp := api.CommitGraphParams{
Action: api.CommitGraphActionWrite,
Reachable: true,
ChangedPaths: true,
SizeMultiple: 4,
Split: ptr.Of(api.CommitGraphSplitOptionEmpty),
}
if p.ReplaceChain {
cgp.Split = ptr.Of(api.CommitGraphSplitOptionReplace)
}
err := s.git.CommitGraph(ctx, repoPath, cgp)
if err != nil {
return fmt.Errorf("writing commit graph failed: %w", err)
}
}
return nil
}
type OptimizationStrategy interface {
ShouldRepackObjects(context.Context) (bool, RepackParams)
ShouldWriteCommitGraph(ctx context.Context) (bool, WriteCommitGraphParams, error)
ShouldPruneObjects(context.Context) (bool, PruneObjectsParams)
ShouldRepackReferences(context.Context) bool
}
type HeuristicalOptimizationStrategy struct {
info api.RepositoryInfo
expireBefore time.Time
}
func NewHeuristicalOptimizationStrategy(
info api.RepositoryInfo,
) HeuristicalOptimizationStrategy {
return HeuristicalOptimizationStrategy{
info: info,
expireBefore: time.Now().Add(api.StaleObjectsGracePeriod),
}
}
func (s HeuristicalOptimizationStrategy) ShouldRepackObjects(
context.Context,
) (bool, RepackParams) {
if s.info.PackFiles.Count == 0 && s.info.LooseObjects.Count == 0 {
return false, RepackParams{}
}
fullRepackParams := RepackParams{
Strategy: RepackStrategyFullWithCruft,
WriteBitmap: true,
WriteMultiPackIndex: true,
CruftExpireBefore: s.expireBefore,
}
nonCruftPackFilesCount := s.info.PackFiles.Count - s.info.PackFiles.CruftCount
timeSinceLastFullRepack := time.Since(s.info.PackFiles.LastFullRepack)
if nonCruftPackFilesCount > 1 && timeSinceLastFullRepack > FullRepackCooldownPeriod {
return true, fullRepackParams
}
geometricRepackParams := RepackParams{
Strategy: RepackStrategyGeometric,
WriteBitmap: true,
WriteMultiPackIndex: true,
}
if !s.info.PackFiles.MultiPackIndex.Exists {
return true, geometricRepackParams
}
allowedLowerLimit := 2.0
allowedUpperLimit := math.Log(float64(s.info.PackFiles.Size)/1024/1024) / math.Log(1.8)
actualLimit := math.Max(allowedLowerLimit, allowedUpperLimit)
untrackedPackfiles := s.info.PackFiles.Count - s.info.PackFiles.MultiPackIndex.PackFileCount
if untrackedPackfiles > uint64(actualLimit) {
return true, geometricRepackParams
}
incrementalRepackParams := RepackParams{
Strategy: RepackStrategyIncrementalWithUnreachable,
WriteBitmap: false,
WriteMultiPackIndex: false,
}
if s.info.LooseObjects.Count > LooseObjectLimit {
return true, incrementalRepackParams
}
return false, fullRepackParams
}
type WriteCommitGraphParams struct {
ReplaceChain bool
}
func (s HeuristicalOptimizationStrategy) ShouldWriteCommitGraph(
ctx context.Context,
) (bool, WriteCommitGraphParams, error) {
if s.info.References.LooseReferenceCount == 0 && s.info.References.PackedReferenceSize == 0 {
return false, WriteCommitGraphParams{}, nil
}
if shouldPrune, _ := s.ShouldPruneObjects(ctx); shouldPrune {
return true, WriteCommitGraphParams{
ReplaceChain: true,
}, nil
}
if needsRepacking, repackCfg := s.ShouldRepackObjects(ctx); needsRepacking {
return true, WriteCommitGraphParams{
ReplaceChain: repackCfg.Strategy == RepackStrategyFullWithCruft && !repackCfg.CruftExpireBefore.IsZero(),
}, nil
}
return false, WriteCommitGraphParams{}, nil
}
type PruneObjectsParams struct {
ExpireBefore time.Time
}
func (s HeuristicalOptimizationStrategy) ShouldPruneObjects(
context.Context,
) (bool, PruneObjectsParams) {
if s.info.LooseObjects.StaleCount < LooseObjectLimit {
return false, PruneObjectsParams{}
}
return true, PruneObjectsParams{
ExpireBefore: s.expireBefore,
}
}
func (s HeuristicalOptimizationStrategy) ShouldRepackReferences(
context.Context,
) bool {
if s.info.References.LooseReferenceCount == 0 {
return false
}
maxVal := max(16, math.Log(float64(s.info.References.PackedReferenceSize)/100)/math.Log(1.15))
if uint64(maxVal) > s.info.References.LooseReferenceCount { //nolint:gosimple
return false
}
return true
}
type FullOptimizationStrategy struct {
info api.RepositoryInfo
expireBefore time.Time
}
func NewFullOptimizationStrategy(
info api.RepositoryInfo,
) FullOptimizationStrategy {
return FullOptimizationStrategy{
info: info,
expireBefore: time.Now().Add(api.StaleObjectsGracePeriod),
}
}
func (s FullOptimizationStrategy) ShouldRepackObjects(
context.Context,
) (bool, RepackParams) {
return true, RepackParams{
Strategy: RepackStrategyFullWithCruft,
WriteBitmap: true,
WriteMultiPackIndex: true,
CruftExpireBefore: s.expireBefore,
}
}
func (s FullOptimizationStrategy) ShouldWriteCommitGraph(
context.Context,
) (bool, WriteCommitGraphParams, error) {
return true, WriteCommitGraphParams{
ReplaceChain: true,
}, nil
}
func (s FullOptimizationStrategy) ShouldPruneObjects(
context.Context,
) (bool, PruneObjectsParams) {
return true, PruneObjectsParams{
ExpireBefore: s.expireBefore,
}
}
func (s FullOptimizationStrategy) ShouldRepackReferences(
context.Context,
) bool {
return true
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.