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/app/api/controller/upload/wire.go
app/api/controller/upload/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 upload import ( "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/blob" "github.com/harness/gitness/types" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideController, ) func ProvideController( authorizer authz.Authorizer, repoFinder refcache.RepoFinder, blobStore blob.Store, config *types.Config, ) *Controller { return NewController(authorizer, repoFinder, blobStore, config) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/upload/controller.go
app/api/controller/upload/controller.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 upload import ( "bufio" "context" "fmt" "io" "strings" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/blob" "github.com/harness/gitness/errors" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/gabriel-vasile/mimetype" ) const ( fileBucketPathFmt = "uploads/%d/%s" peekBytes = 512 ) var supportedFileTypes = map[string]struct{}{ "image": {}, "video": {}, } type Controller struct { authorizer authz.Authorizer repoFinder refcache.RepoFinder blobStore blob.Store blobMaxSize int64 } func NewController( authorizer authz.Authorizer, repoFinder refcache.RepoFinder, blobStore blob.Store, config *types.Config, ) *Controller { return &Controller{ authorizer: authorizer, repoFinder: repoFinder, blobStore: blobStore, blobMaxSize: config.BlobStore.MaxFileSize, } } func (c *Controller) GetMaxFileSize() int64 { return c.blobMaxSize } //nolint:unparam func (c *Controller) getRepoCheckAccess(ctx context.Context, session *auth.Session, repoRef string, permission enum.Permission, allowedRepoStates ...enum.RepoState, ) (*types.RepositoryCore, error) { if repoRef == "" { return nil, usererror.BadRequest("A valid repository reference must be provided.") } repo, err := c.repoFinder.FindByRef(ctx, repoRef) if err != nil { return nil, fmt.Errorf("failed to find repo: %w", err) } if err := apiauth.CheckRepoState(ctx, session, repo, permission, allowedRepoStates...); err != nil { return nil, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, permission); err != nil { return nil, fmt.Errorf("failed to verify authorization: %w", err) } return repo, nil } func (c *Controller) getFileExtension(file *bufio.Reader) (string, error) { buf, err := file.Peek(peekBytes) if err != nil && !errors.Is(err, io.EOF) { return "", fmt.Errorf("failed to read file: %w", err) } // Example: mType.String() = image/png // Splitting on "/" and taking the first element of the slice // will give us the file type. mType := mimetype.Detect(buf) if _, ok := supportedFileTypes[strings.Split(mType.String(), "/")[0]]; !ok { return "", usererror.BadRequestf( "only image and video files are supported, uploaded file is of type %s", mType.String()) } return mType.Extension(), nil } func getFileBucketPath(repoID int64, fileName string) string { return fmt.Sprintf(fileBucketPathFmt, repoID, fileName) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/upload/upload.go
app/api/controller/upload/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 upload import ( "bufio" "context" "fmt" "io" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" "github.com/google/uuid" ) // Result contains the information about the upload. type Result struct { FilePath string `json:"file_path"` } func (c *Controller) Upload(ctx context.Context, session *auth.Session, repoRef string, file io.Reader, ) (*Result, error) { // Permission check to see if the user in request has access to the repo. repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } if file == nil { return nil, usererror.BadRequest("No file provided") } bufReader := bufio.NewReader(file) // Check if the file is an image or video extn, err := c.getFileExtension(bufReader) if err != nil { return nil, fmt.Errorf("failed to determine file type: %w", err) } identifier := uuid.New().String() fileName := identifier + extn fileBucketPath := getFileBucketPath(repo.ID, fileName) err = c.blobStore.Upload(ctx, bufReader, fileBucketPath) if err != nil { return nil, fmt.Errorf("failed to upload file: %w", err) } return &Result{ FilePath: fileName, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/upload/download.go
app/api/controller/upload/download.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 upload import ( "context" "errors" "fmt" "io" "time" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/blob" "github.com/harness/gitness/types/enum" ) func (c *Controller) Download( ctx context.Context, session *auth.Session, repoRef string, filePath string, ) (string, io.ReadCloser, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return "", nil, fmt.Errorf("failed to acquire access to repo: %w", err) } fileBucketPath := getFileBucketPath(repo.ID, filePath) signedURL, err := c.blobStore.GetSignedURL(ctx, fileBucketPath, time.Now().Add(1*time.Hour)) if err != nil && !errors.Is(err, blob.ErrNotSupported) { return "", nil, fmt.Errorf("failed to get signed URL: %w", err) } if signedURL != "" { return signedURL, nil, nil } file, err := c.blobStore.Download(ctx, fileBucketPath) if err != nil { return "", nil, fmt.Errorf("failed to download file from blobstore: %w", err) } return "", file, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/check/check_list.go
app/api/controller/check/check_list.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 check import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListChecks return an array of status check results for a commit in a repository. func (c *Controller) ListChecks( ctx context.Context, session *auth.Session, repoRef string, commitSHA string, opts types.CheckListOptions, ) ([]types.Check, int, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to repo: %w", err) } var checks []types.Check var count int err = c.tx.WithTx(ctx, func(ctx context.Context) (err error) { checks, err = c.checkStore.List(ctx, repo.ID, commitSHA, opts) if err != nil { return fmt.Errorf("failed to list status check results for repo=%s: %w", repo.Identifier, err) } if opts.Page == 1 && len(checks) < opts.Size { count = len(checks) return nil } count, err = c.checkStore.Count(ctx, repo.ID, commitSHA, opts) if err != nil { return fmt.Errorf("failed to count status check results for repo=%s: %w", repo.Identifier, err) } return nil }) if err != nil { return nil, 0, err } return checks, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/check/wire.go
app/api/controller/check/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 check import ( "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth/authz" checkevents "github.com/harness/gitness/app/events/check" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/git" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types/enum" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideCheckSanitizers, ProvideController, ) func ProvideController( tx dbtx.Transactor, authorizer authz.Authorizer, spaceStore store.SpaceStore, checkStore store.CheckStore, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder, git git.Interface, sanitizers map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error, sseStreamer sse.Streamer, eventReporter *checkevents.Reporter, ) *Controller { return NewController( tx, authorizer, spaceStore, checkStore, spaceFinder, repoFinder, git, sanitizers, sseStreamer, eventReporter, ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/check/check_report_test.go
app/api/controller/check/check_report_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 check import ( "testing" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func Test_getStartedTime(t *testing.T) { type args struct { in *ReportInput check types.Check now int64 } tests := []struct { name string args args want int64 }{ { name: "nothing to pending", args: args{ in: &ReportInput{Status: enum.CheckStatusPending}, check: types.Check{}, now: 1234, }, want: 0, }, { name: "nothing to running", args: args{ in: &ReportInput{Status: enum.CheckStatusRunning}, check: types.Check{}, now: 1234, }, want: 1234, }, { name: "nothing to completed", args: args{ in: &ReportInput{Status: enum.CheckStatusSuccess}, check: types.Check{}, now: 1234, }, want: 1234, }, { name: "nothing to completed1", args: args{ in: &ReportInput{Status: enum.CheckStatusSuccess, Started: 1}, check: types.Check{}, now: 1234, }, want: 1, }, { name: "pending to pending", args: args{ in: &ReportInput{Status: enum.CheckStatusPending, Started: 1}, check: types.Check{Status: enum.CheckStatusPending, Started: 0}, now: 1234, }, want: 1, }, { name: "pending to pending1", args: args{ in: &ReportInput{Status: enum.CheckStatusPending}, check: types.Check{Status: enum.CheckStatusPending, Started: 0}, now: 1234, }, want: 0, }, { name: "pending to running", args: args{ in: &ReportInput{Status: enum.CheckStatusRunning}, check: types.Check{Status: enum.CheckStatusPending, Started: 0}, now: 1234, }, want: 1234, }, { name: "pending to running1", args: args{ in: &ReportInput{Status: enum.CheckStatusRunning, Started: 1}, check: types.Check{Status: enum.CheckStatusPending, Started: 0}, now: 1234, }, want: 1, }, { name: "pending to completed", args: args{ in: &ReportInput{Status: enum.CheckStatusSuccess, Started: 1}, check: types.Check{Status: enum.CheckStatusPending, Started: 0}, now: 1234, }, want: 1, }, { name: "pending to completed1", args: args{ in: &ReportInput{Status: enum.CheckStatusSuccess}, check: types.Check{Status: enum.CheckStatusPending, Started: 0}, now: 1234, }, want: 1234, }, { name: "running to pending", args: args{ in: &ReportInput{Status: enum.CheckStatusPending, Started: 1}, check: types.Check{Status: enum.CheckStatusRunning, Started: 9876}, now: 1234, }, want: 1, }, { name: "running to pending1", args: args{ in: &ReportInput{Status: enum.CheckStatusPending}, check: types.Check{Status: enum.CheckStatusRunning, Started: 9876}, now: 1234, }, want: 0, }, { name: "running to running", args: args{ in: &ReportInput{Status: enum.CheckStatusRunning}, check: types.Check{Status: enum.CheckStatusRunning, Started: 9876}, now: 1234, }, want: 9876, }, { name: "running to running1", args: args{ in: &ReportInput{Status: enum.CheckStatusRunning, Started: 1}, check: types.Check{Status: enum.CheckStatusRunning, Started: 9876}, now: 1234, }, want: 1, }, { name: "running to completed", args: args{ in: &ReportInput{Status: enum.CheckStatusSuccess}, check: types.Check{Status: enum.CheckStatusRunning, Started: 9876}, now: 1234, }, want: 9876, }, { name: "running to completed", args: args{ in: &ReportInput{Status: enum.CheckStatusSuccess, Started: 1}, check: types.Check{Status: enum.CheckStatusRunning, Started: 9876}, now: 1234, }, want: 1, }, { name: "completed to pending", args: args{ in: &ReportInput{Status: enum.CheckStatusPending}, check: types.Check{Status: enum.CheckStatusSuccess, Started: 9876}, now: 1234, }, want: 0, }, { name: "completed to running", args: args{ in: &ReportInput{Status: enum.CheckStatusRunning}, check: types.Check{Status: enum.CheckStatusSuccess, Started: 9876}, now: 1234, }, want: 1234, }, { name: "completed to completed", args: args{ in: &ReportInput{Status: enum.CheckStatusSuccess}, check: types.Check{Status: enum.CheckStatusSuccess, Started: 9876}, now: 1234, }, want: 1234, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := getStartTime(tt.args.in, tt.args.check, tt.args.now); got != tt.want { t.Errorf("getStartTime() = %v, want %v", got, tt.want) } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/check/check_report.go
app/api/controller/check/check_report.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 check import ( "bytes" "context" "encoding/json" "errors" "fmt" "regexp" "time" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" events "github.com/harness/gitness/app/events/check" "github.com/harness/gitness/git" "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type ReportInput struct { // TODO [CODE-1363]: remove after identifier migration. CheckUID string `json:"check_uid" deprecated:"true"` Identifier string `json:"identifier"` Status enum.CheckStatus `json:"status"` Summary string `json:"summary"` Link string `json:"link"` Payload types.CheckPayload `json:"payload"` Started int64 `json:"started,omitempty"` Ended int64 `json:"ended,omitempty"` } // TODO: Can we drop the '$' - depends on whether harness allows it. var regexpCheckIdentifier = "^[0-9a-zA-Z-_.$]{1,127}$" var matcherCheckIdentifier = regexp.MustCompile(regexpCheckIdentifier) // Sanitize validates and sanitizes the ReportInput data. func (in *ReportInput) Sanitize( sanitizers map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error, session *auth.Session, ) error { // TODO [CODE-1363]: remove after identifier migration. if in.Identifier == "" { in.Identifier = in.CheckUID } if in.Identifier == "" { return usererror.BadRequest("Identifier is missing") } if !matcherCheckIdentifier.MatchString(in.Identifier) { return usererror.BadRequestf("Identifier must match the regular expression: %s", regexpCheckIdentifier) } _, ok := in.Status.Sanitize() if !ok { return usererror.BadRequest("Invalid value provided for status check status") } validatorFn, ok := sanitizers[in.Payload.Kind] if !ok { return usererror.BadRequest("Invalid value provided for the payload kind") } // Validate and sanitize the input data based on version; Require a link... and similar operations. if err := validatorFn(in, session); err != nil { return fmt.Errorf("payload validation failed: %w", err) } if in.Ended != 0 && in.Ended < in.Started { return usererror.BadRequest("Started time reported after ended time") } return nil } func SanitizeJSONPayload(source json.RawMessage, data any) (json.RawMessage, error) { if len(source) == 0 { return json.Marshal(data) // marshal the empty object } decoder := json.NewDecoder(bytes.NewReader(source)) decoder.DisallowUnknownFields() if err := decoder.Decode(&data); err != nil { return nil, usererror.BadRequestf("Payload data doesn't match the required format: %s", err.Error()) } buffer := bytes.NewBuffer(nil) buffer.Grow(512) encoder := json.NewEncoder(buffer) encoder.SetEscapeHTML(false) if err := encoder.Encode(data); err != nil { return nil, fmt.Errorf("failed to sanitize json payload: %w", err) } result := buffer.Bytes() if result[len(result)-1] == '\n' { result = result[:len(result)-1] } return result, nil } // Report modifies an existing or creates a new (if none yet exists) status check report for a specific commit. func (c *Controller) Report( ctx context.Context, session *auth.Session, repoRef string, commitSHA string, in *ReportInput, metadata map[string]string, ) (*types.Check, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReportCommitCheck) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } if errValidate := in.Sanitize(c.sanitizers, session); errValidate != nil { return nil, errValidate } if !git.ValidateCommitSHA(commitSHA) { return nil, usererror.BadRequest("Invalid commit SHA provided") } _, err = c.git.GetCommit(ctx, &git.GetCommitParams{ ReadParams: git.ReadParams{RepoUID: repo.GitUID}, Revision: commitSHA, }) if err != nil { return nil, fmt.Errorf("failed to commit sha=%s: %w", commitSHA, err) } now := time.Now().UnixMilli() metadataJSON, _ := json.Marshal(metadata) existingCheck, err := c.checkStore.FindByIdentifier(ctx, repo.ID, commitSHA, in.Identifier) if err != nil && !errors.Is(err, store.ErrResourceNotFound) { return nil, fmt.Errorf("failed to find existing check for Identifier %q: %w", in.Identifier, err) } started := getStartTime(in, existingCheck, now) ended := getEndTime(in, now) statusCheckReport := &types.Check{ CreatedBy: session.Principal.ID, Created: now, Updated: now, RepoID: repo.ID, CommitSHA: commitSHA, Identifier: in.Identifier, Status: in.Status, Summary: in.Summary, Link: in.Link, Payload: in.Payload, Metadata: metadataJSON, ReportedBy: session.Principal.ToPrincipalInfo(), Started: started, Ended: ended, } err = c.checkStore.Upsert(ctx, statusCheckReport) if err != nil { return nil, fmt.Errorf("failed to upsert status check result for repo=%s: %w", repo.Identifier, err) } c.eventReporter.Reported(ctx, &events.ReportedPayload{ Base: events.Base{ RepoID: repo.ID, SHA: commitSHA, }, Identifier: in.Identifier, Status: in.Status, }) c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypeStatusCheckReportUpdated, statusCheckReport) return statusCheckReport, nil } func getStartTime(in *ReportInput, check types.Check, now int64) int64 { // start value came in api if in.Started != 0 { return in.Started } // in.started has no value we smartly put value for started // in case of pending we assume check has not started running if in.Status == enum.CheckStatusPending { return 0 } // new check if check.Started == 0 { return now } // The incoming check status can now be running or terminal. // in case we already have running status we don't update time else we return current time as check has started // running. if check.Status == enum.CheckStatusRunning { return check.Started } // Note: In case of reporting terminal statuses again and again we have assumed its // a report of new status check everytime. // In case someone reports any status before marking running return current time. // This can happen if someone only reports terminal status or marks running status again after terminal. return now } func getEndTime(in *ReportInput, now int64) int64 { // end value came in api if in.Ended != 0 { return in.Ended } // if we get terminal status i.e. error, failure or success we return current time. if in.Status.IsCompleted() { return now } // in case of other status we return value as 0, which means we have not yet completed the check. return 0 }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/check/controller.go
app/api/controller/check/controller.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 check import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/controller/space" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth/authz" checkevents "github.com/harness/gitness/app/events/check" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/git" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type Controller struct { tx dbtx.Transactor authorizer authz.Authorizer spaceStore store.SpaceStore checkStore store.CheckStore spaceFinder refcache.SpaceFinder repoFinder refcache.RepoFinder git git.Interface sanitizers map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error sseStreamer sse.Streamer eventReporter *checkevents.Reporter } func NewController( tx dbtx.Transactor, authorizer authz.Authorizer, spaceStore store.SpaceStore, checkStore store.CheckStore, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder, git git.Interface, sanitizers map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error, sseStreamer sse.Streamer, eventReporter *checkevents.Reporter, ) *Controller { return &Controller{ tx: tx, authorizer: authorizer, spaceStore: spaceStore, checkStore: checkStore, spaceFinder: spaceFinder, repoFinder: repoFinder, git: git, sanitizers: sanitizers, sseStreamer: sseStreamer, eventReporter: eventReporter, } } //nolint:unparam func (c *Controller) getRepoCheckAccess( ctx context.Context, session *auth.Session, repoRef string, reqPermission enum.Permission, allowedRepoStates ...enum.RepoState, ) (*types.RepositoryCore, error) { if repoRef == "" { return nil, usererror.BadRequest("A valid repository reference must be provided.") } repo, err := c.repoFinder.FindByRef(ctx, repoRef) if err != nil { return nil, fmt.Errorf("failed to find repository: %w", err) } if err := apiauth.CheckRepoState(ctx, session, repo, reqPermission, allowedRepoStates...); err != nil { return nil, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, reqPermission); err != nil { return nil, fmt.Errorf("access check failed: %w", err) } return repo, nil } func (c *Controller) getSpaceCheckAccess( ctx context.Context, session *auth.Session, spaceRef string, permission enum.Permission, ) (*types.SpaceCore, error) { return space.GetSpaceCheckAuth(ctx, c.spaceFinder, c.authorizer, session, spaceRef, permission) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/check/check_recent_space.go
app/api/controller/check/check_recent_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 check import ( "context" "fmt" "time" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListRecentChecksSpace return an array of status check UIDs that have been run recently. func (c *Controller) ListRecentChecksSpace( ctx context.Context, session *auth.Session, spaceRef string, recursive bool, opts types.CheckRecentOptions, ) ([]string, error) { space, err := c.getSpaceCheckAccess(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } if opts.Since == 0 { opts.Since = time.Now().Add(-30 * 24 * time.Hour).UnixMilli() } var spaceIDs []int64 if recursive { spaceIDs, err = c.spaceStore.GetDescendantsIDs(ctx, space.ID) if err != nil { return nil, fmt.Errorf("failed to get space descendants ids: %w", err) } } else { spaceIDs = append(spaceIDs, space.ID) } checkIdentifiers, err := c.checkStore.ListRecentSpace(ctx, spaceIDs, opts) if err != nil { return nil, fmt.Errorf( "failed to list status check results for space=%s: %w", space.Identifier, err, ) } return checkIdentifiers, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/check/sanitizers.go
app/api/controller/check/sanitizers.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 check import ( "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func ProvideCheckSanitizers() map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error { registeredCheckSanitizers := make(map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error) registeredCheckSanitizers[enum.CheckPayloadKindEmpty] = createEmptyPayloadSanitizer() registeredCheckSanitizers[enum.CheckPayloadKindRaw] = createRawPayloadSanitizer() // Markdown and Raw are the same. registeredCheckSanitizers[enum.CheckPayloadKindMarkdown] = registeredCheckSanitizers[enum.CheckPayloadKindRaw] registeredCheckSanitizers[enum.CheckPayloadKindPipeline] = createPipelinePayloadSanitizer() return registeredCheckSanitizers } func createEmptyPayloadSanitizer() func(in *ReportInput, _ *auth.Session) error { return func(in *ReportInput, _ *auth.Session) error { // the default payload kind (empty) does not support the payload data: clear it here in.Payload.Version = "" in.Payload.Data = []byte("{}") if in.Link == "" { // the link is mandatory as there is nothing in the payload return usererror.BadRequest("Link is missing") } return nil } } func createRawPayloadSanitizer() func(in *ReportInput, _ *auth.Session) error { return func(in *ReportInput, _ *auth.Session) error { // the text payload kinds (raw and markdown) do not support the version if in.Payload.Version != "" { return usererror.BadRequestf("Payload version must be empty for the payload kind '%s'", in.Payload.Kind) } payloadDataJSON, err := SanitizeJSONPayload(in.Payload.Data, &types.CheckPayloadText{}) if err != nil { return err } in.Payload.Data = payloadDataJSON return nil } } func createPipelinePayloadSanitizer() func(in *ReportInput, _ *auth.Session) error { return func(_ *ReportInput, _ *auth.Session) error { return usererror.BadRequest("Kind cannot be pipeline for external checks") } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/check/check_recent.go
app/api/controller/check/check_recent.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 check import ( "context" "fmt" "time" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListRecentChecks return an array of status check UIDs that have been run recently. func (c *Controller) ListRecentChecks( ctx context.Context, session *auth.Session, repoRef string, opts types.CheckRecentOptions, ) ([]string, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } if opts.Since == 0 { opts.Since = time.Now().Add(-30 * 24 * time.Hour).UnixMilli() } checkIdentifiers, err := c.checkStore.ListRecent(ctx, repo.ID, opts) if err != nil { return nil, fmt.Errorf("failed to list status check results for repo=%s: %w", repo.Identifier, err) } return checkIdentifiers, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/check_list.go
app/api/controller/pullreq/check_list.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 pullreq import ( "context" "encoding/json" "fmt" "sort" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListChecks return an array of status check results for a commit in a repository. func (c *Controller) ListChecks( ctx context.Context, session *auth.Session, repoRef string, prNum int64, ) (types.PullReqChecks, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return types.PullReqChecks{}, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return types.PullReqChecks{}, fmt.Errorf("failed to find pull request by number: %w", err) } protectionRules, isRepoOwner, err := c.fetchRules(ctx, session, repo) if err != nil { return types.PullReqChecks{}, fmt.Errorf("failed to fetch rules: %w", err) } reqChecks, err := protectionRules.RequiredChecks(ctx, protection.RequiredChecksInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, IsRepoOwner: isRepoOwner, Repo: repo, PullReq: pr, }) if err != nil { return types.PullReqChecks{}, fmt.Errorf("failed to get identifiers of required checks: %w", err) } commitSHA := pr.SourceSHA checks, err := c.checkStore.List(ctx, repo.ID, commitSHA, types.CheckListOptions{}) if err != nil { return types.PullReqChecks{}, fmt.Errorf("failed to list status check results for repo: %w", err) } result := types.PullReqChecks{ CommitSHA: commitSHA, Checks: nil, } for _, check := range checks { _, required := reqChecks.RequiredIdentifiers[check.Identifier] if required { delete(reqChecks.RequiredIdentifiers, check.Identifier) } _, bypassable := reqChecks.BypassableIdentifiers[check.Identifier] if bypassable { delete(reqChecks.BypassableIdentifiers, check.Identifier) } result.Checks = append(result.Checks, types.PullReqCheck{ Required: required || bypassable, Bypassable: bypassable, Check: check, }) } for requiredID := range reqChecks.RequiredIdentifiers { result.Checks = append(result.Checks, types.PullReqCheck{ Required: true, Bypassable: false, Check: types.Check{ RepoID: repo.ID, CommitSHA: commitSHA, Identifier: requiredID, Status: enum.CheckStatusPending, Metadata: json.RawMessage("{}"), }, }) } for bypassableID := range reqChecks.BypassableIdentifiers { result.Checks = append(result.Checks, types.PullReqCheck{ Required: true, Bypassable: true, Check: types.Check{ RepoID: repo.ID, CommitSHA: commitSHA, Identifier: bypassableID, Status: enum.CheckStatusPending, Metadata: json.RawMessage("{}"), }, }) } // Note: The DB List method sorts by "check_updated desc", but here we sort by Identifier, // because we extended the list to include required elements not yet reported (their check_updated timestamp is 0). sort.Slice(result.Checks, func(i, j int) bool { return result.Checks[i].Check.Identifier < result.Checks[j].Check.Identifier }) return result, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/merge.go
app/api/controller/pullreq/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 pullreq import ( "context" "fmt" "strconv" "strings" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/codeowners" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/app/services/pullreq" "github.com/harness/gitness/audit" "github.com/harness/gitness/contextutil" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" gitapi "github.com/harness/gitness/git/api" gitenum "github.com/harness/gitness/git/enum" "github.com/harness/gitness/git/sha" gitness_store "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/gotidy/ptr" "github.com/rs/zerolog/log" "golang.org/x/exp/maps" ) type MergeInput struct { Method enum.MergeMethod `json:"method"` SourceSHA string `json:"source_sha"` Title string `json:"title"` Message string `json:"message"` DeleteSourceBranch bool `json:"delete_source_branch"` BypassRules bool `json:"bypass_rules"` DryRun bool `json:"dry_run"` DryRunRules bool `json:"dry_run_rules"` } func (in *MergeInput) sanitize() error { if in.Method == "" && !in.DryRun && !in.DryRunRules { return usererror.BadRequest("Merge method must be provided if dry run is false") } if in.SourceSHA == "" { return usererror.BadRequest("Source SHA must be provided") } if in.Method != "" { method, ok := in.Method.Sanitize() if !ok { return usererror.BadRequestf("Unsupported merge method: %q", in.Method) } in.Method = method } // cleanup title / message (NOTE: git doesn't support white space only) in.Title = strings.TrimSpace(in.Title) in.Message = strings.TrimSpace(in.Message) if (in.Method == enum.MergeMethodRebase || in.Method == enum.MergeMethodFastForward) && (in.Title != "" || in.Message != "") { return usererror.BadRequestf( "merge method %q doesn't support customizing commit title and message", in.Method) } return nil } // backfillApprovalInfo populates principal and user group information for default reviewer approvals. func (c *Controller) backfillApprovalInfo( ctx context.Context, approvals []*types.DefaultReviewerApprovalsResponse, ) error { for _, approval := range approvals { principalInfos, err := c.principalInfoCache.Map(ctx, approval.PrincipalIDs) if err != nil { return fmt.Errorf("failed to fetch principal infos from info cache: %w", err) } approval.PrincipalInfos = maps.Values(principalInfos) userGroups, err := c.userGroupStore.FindManyByIDs(ctx, approval.UserGroupIDs) if err != nil { return fmt.Errorf("failed to fetch user groups info from user group store: %w", err) } userGroupInfos := make([]*types.UserGroupInfo, 0, len(userGroups)) for _, ug := range userGroups { userGroupInfos = append(userGroupInfos, ug.ToUserGroupInfo()) } approval.UserGroupInfos = userGroupInfos } return nil } // Merge merges a pull request. // // It supports dry running by providing the DryRun=true. Dry running can be used to find any rule violations that // might block the merging. Dry running typically should be used with BypassRules=true. // // MergeMethod doesn't need to be provided for dry running. If no MergeMethod has been provided the function will // return allowed merge methods. Rules can limit allowed merge methods. // // If the pull request has been successfully merged the function will return the SHA of the merge commit. // //nolint:gocognit,gocyclo,cyclop func (c *Controller) Merge( ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, in *MergeInput, ) (*types.MergeResponse, *types.MergeViolations, error) { if err := in.sanitize(); err != nil { return nil, nil, err } requiredPermission := enum.PermissionRepoPush if in.DryRunRules || in.DryRun { requiredPermission = enum.PermissionRepoView } targetRepo, err := c.getRepoCheckAccess(ctx, session, repoRef, requiredPermission) if err != nil { return nil, nil, fmt.Errorf("failed to acquire access to target repo: %w", err) } // the max time we give a merge to succeed const timeout = 3 * time.Minute // lock the repo only if actual git merge would be attempted if !in.DryRunRules { var lockID int64 // 0 means locking repo level for prs (for actual merging) if in.DryRun { lockID = pullreqNum // dryrun doesn't need repo level lock } // if two requests for merging comes at the same time then unlock will lock // first one and second one will wait, when first one is done then second one // continue with latest data from db with state merged and return error that // pr is already merged. unlock, err := c.locker.LockPR( ctx, targetRepo.ID, lockID, timeout+30*time.Second, // add 30s to the lock to give enough time for pre + post merge ) if err != nil { return nil, nil, fmt.Errorf("failed to lock repository for pull request merge: %w", err) } defer unlock() } pr, err := c.pullreqStore.FindByNumber(ctx, targetRepo.ID, pullreqNum) if err != nil { return nil, nil, fmt.Errorf("failed to get pull request by number: %w", err) } if pr.Merged != nil { return nil, nil, usererror.BadRequest("Pull request already merged") } if pr.State != enum.PullReqStateOpen { return nil, nil, usererror.BadRequest("Pull request must be open") } if pr.SourceSHA != in.SourceSHA { return nil, nil, usererror.BadRequest("A newer commit is available. Only the latest commit can be merged.") } if pr.IsDraft && !in.DryRunRules && !in.DryRun { return nil, nil, usererror.BadRequest( "Draft pull requests can't be merged. Clear the draft flag first.", ) } reviewers, err := c.reviewerStore.List(ctx, pr.ID) if err != nil { return nil, nil, fmt.Errorf("failed to load list of reviwers: %w", err) } targetWriteParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, targetRepo) if err != nil { return nil, nil, fmt.Errorf("failed to create RPC write params: %w", err) } var sourceRepo *types.RepositoryCore var sourceWriteParams git.WriteParams switch { case pr.SourceRepoID == nil: // the source repo is purged case *pr.SourceRepoID != pr.TargetRepoID: // if the source repo is nil, it's soft deleted sourceRepo, err = c.repoFinder.FindByID(ctx, *pr.SourceRepoID) if err != nil && !errors.Is(err, gitness_store.ErrResourceNotFound) { return nil, nil, fmt.Errorf("failed to get source repository: %w", err) } if sourceRepo != nil { sourceWriteParams, err = controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, sourceRepo) if err != nil { return nil, nil, fmt.Errorf("failed to create RPC write params: %w", err) } } default: sourceRepo = targetRepo sourceWriteParams = targetWriteParams } getHeadRef, err := c.git.GetRef(ctx, git.GetRefParams{ ReadParams: git.ReadParams{RepoUID: targetRepo.GitUID}, Name: strconv.FormatInt(pr.Number, 10), Type: gitenum.RefTypePullReqHead, }) if err != nil { return nil, nil, fmt.Errorf("failed to get pull request head ref: %w", err) } if getHeadRef.SHA != sha.Must(pr.SourceSHA) { return nil, nil, usererror.BadRequest("The pull request head ref doesn't match the source SHA.") } sourceSHA := getHeadRef.SHA protectionRules, isRepoOwner, err := c.fetchRules(ctx, session, targetRepo) if err != nil { return nil, nil, fmt.Errorf("failed to fetch rules: %w", err) } checkResults, err := c.checkStore.ListResults(ctx, targetRepo.ID, in.SourceSHA) if err != nil { return nil, nil, fmt.Errorf("failed to list status checks: %w", err) } codeOwnerWithApproval, err := c.codeOwners.Evaluate(ctx, targetRepo, pr, reviewers) // check for error and ignore if it is codeowners file not found else throw error if err != nil && !errors.Is(err, codeowners.ErrNotFound) { return nil, nil, fmt.Errorf("CODEOWNERS evaluation failed: %w", err) } ruleOut, violations, err := protectionRules.MergeVerify(ctx, protection.MergeVerifyInput{ ResolveUserGroupIDs: c.userGroupService.ListUserIDsByGroupIDs, MapUserGroupIDs: c.userGroupService.MapGroupIDsToPrincipals, Actor: &session.Principal, AllowBypass: in.BypassRules, IsRepoOwner: isRepoOwner, TargetRepo: targetRepo, SourceRepo: sourceRepo, PullReq: pr, Reviewers: reviewers, Method: in.Method, CheckResults: checkResults, CodeOwners: codeOwnerWithApproval, }) if err != nil { return nil, nil, fmt.Errorf("failed to verify protection rules: %w", err) } // only delete the source branch if it's the source repository is the same as the target repository. deleteSourceBranch := pr.SourceRepoID != nil && pr.TargetRepoID == *pr.SourceRepoID && (in.DeleteSourceBranch || ruleOut.DeleteSourceBranch) if in.DryRunRules { err := c.backfillApprovalInfo(ctx, ruleOut.DefaultReviewerApprovals) if err != nil { return nil, nil, fmt.Errorf("failed to populate approval info for default reviewers: %w", err) } return &types.MergeResponse{ BranchDeleted: deleteSourceBranch, RuleViolations: violations, DryRunRules: true, AllowedMethods: ruleOut.AllowedMethods, RequiresCodeOwnersApproval: ruleOut.RequiresCodeOwnersApproval, RequiresCodeOwnersApprovalLatest: ruleOut.RequiresCodeOwnersApprovalLatest, RequiresCommentResolution: ruleOut.RequiresCommentResolution, RequiresNoChangeRequests: ruleOut.RequiresNoChangeRequests, MinimumRequiredApprovalsCount: ruleOut.MinimumRequiredApprovalsCount, MinimumRequiredApprovalsCountLatest: ruleOut.MinimumRequiredApprovalsCountLatest, DefaultReviewerApprovals: ruleOut.DefaultReviewerApprovals, }, nil, nil } targetBranch, err := c.git.GetBranch(ctx, &git.GetBranchParams{ ReadParams: git.ReadParams{RepoUID: targetRepo.GitUID}, BranchName: pr.TargetBranch, }) if err != nil { return nil, nil, fmt.Errorf("failed to get pull request target branch: %w", err) } targetSHA := targetBranch.Branch.SHA // we want to complete the merge independent of request cancel - start with new, time restricted context. // TODO: This is a small change to reduce likelihood of dirty state. // We still require a proper solution to handle an application crash or very slow execution times // (which could cause an unlocking pre operation completion). ctx, cancel := contextutil.WithNewTimeout(ctx, timeout) defer cancel() //nolint:nestif if in.DryRun { // As the merge API is always executed under a global lock, we use the opportunity of dry-running the merge // to check the PR's mergeability status if it's currently "unchecked". This can happen if the target branch // has advanced. It's possible that the merge base commit is different too. // So, the next time the API gets called for the same PR the mergeability status will not be unchecked. // Without dry-run the execution would proceed below and would either merge the PR or set the conflict status. var mergeOutput git.MergeOutput // We distinguish two types when checking mergeability: Rebase and Non-Rebase. // * Merge methods Merge and Squash will always have the same results. // * Merge method Rebase is special because it must always check all commits, one at a time. // * Merge method Fast-Forward can never have conflicts, // but for it the merge base SHA must be equal to target branch SHA. // The result of the tests will be stored (think cached) in the database for these two types // in the fields merge_check_status and rebase_check_status. if in.Method == "" { in.Method = enum.MergeMethodMerge } checkMergeability := func(method enum.MergeMethod) bool { switch method { case enum.MergeMethodMerge, enum.MergeMethodSquash: return pr.MergeCheckStatus == enum.MergeCheckStatusUnchecked case enum.MergeMethodRebase: return pr.RebaseCheckStatus == enum.MergeCheckStatusUnchecked case enum.MergeMethodFastForward: // Always check for ff merge. There can never be conflicts, // but we are interested in if it returns the conflict error and merge-output data. return true default: return true // should not happen } }(in.Method) if checkMergeability { // for merge-check we can skip git hooks explicitly (we don't update any refs anyway) writeParams, err := controller.CreateRPCSystemReferencesWriteParams(ctx, c.urlProvider, session, targetRepo) if err != nil { return nil, nil, fmt.Errorf("failed to create RPC write params: %w", err) } mergeOutput, err = c.git.Merge(ctx, &git.MergeParams{ WriteParams: writeParams, BaseSHA: targetSHA, HeadSHA: sourceSHA, Refs: nil, // update no refs -> no commit will be created Method: gitenum.MergeMethod(in.Method), }) if errors.IsInvalidArgument(err) || gitapi.IsUnrelatedHistoriesError(err) { inClose := pullreq.NonUniqueMergeBaseInput{ PullReqStore: c.pullreqStore, ActivityStore: c.activityStore, PullReqEvReporter: c.eventReporter, SSEStreamer: c.sseStreamer, } errClose := pullreq.CloseBecauseNonUniqueMergeBase(ctx, inClose, targetSHA, sourceSHA, pr) if errClose != nil { return nil, nil, fmt.Errorf("failed to close pull request after non-unique merge base: %w", errClose) } return nil, nil, err } if err != nil { return nil, nil, fmt.Errorf("failed merge check with method=%s: %w", in.Method, err) } pr, err = c.pullreqStore.UpdateMergeCheckMetadataOptLock(ctx, pr, func(pr *types.PullReq) error { if pr.SourceSHA != mergeOutput.HeadSHA.String() { return errors.New("source SHA has changed") } // actual merge is using a different lock - ensure we don't overwrite any merge results. if pr.State != enum.PullReqStateOpen { return usererror.BadRequest("Pull request must be open") } pr.MergeBaseSHA = mergeOutput.MergeBaseSHA.String() pr.MergeTargetSHA = ptr.String(mergeOutput.BaseSHA.String()) pr.MergeSHA = nil // dry-run doesn't create a merge commit so output is empty. pr.UpdateMergeOutcome(in.Method, mergeOutput.ConflictFiles) pr.Stats.DiffStats = types.NewDiffStats( mergeOutput.CommitCount, mergeOutput.ChangedFileCount, mergeOutput.Additions, mergeOutput.Deletions, ) return nil }) if err != nil { // non-critical error log.Ctx(ctx).Warn().Err(err).Msg("failed to update unchecked pull request") } else { c.sseStreamer.Publish(ctx, targetRepo.ParentID, enum.SSETypePullReqUpdated, pr) } } var conflicts []string if in.Method == enum.MergeMethodRebase { conflicts = pr.RebaseConflicts } else { conflicts = pr.MergeConflicts } err := c.backfillApprovalInfo(ctx, ruleOut.DefaultReviewerApprovals) if err != nil { return nil, nil, fmt.Errorf("failed to populate approval info for default reviewers: %w", err) } // With in.DryRun=true this function never returns types.MergeViolations out := &types.MergeResponse{ BranchDeleted: deleteSourceBranch, RuleViolations: violations, // values only returned by dry run DryRun: true, Mergeable: len(conflicts) == 0, ConflictFiles: conflicts, AllowedMethods: ruleOut.AllowedMethods, RequiresCodeOwnersApproval: ruleOut.RequiresCodeOwnersApproval, RequiresCodeOwnersApprovalLatest: ruleOut.RequiresCodeOwnersApprovalLatest, RequiresCommentResolution: ruleOut.RequiresCommentResolution, RequiresNoChangeRequests: ruleOut.RequiresNoChangeRequests, MinimumRequiredApprovalsCount: ruleOut.MinimumRequiredApprovalsCount, MinimumRequiredApprovalsCountLatest: ruleOut.MinimumRequiredApprovalsCountLatest, DefaultReviewerApprovals: ruleOut.DefaultReviewerApprovals, } return out, nil, nil } if protection.IsCritical(violations) { sb := strings.Builder{} for i, ruleViolation := range violations { if i > 0 { sb.WriteByte(',') } sb.WriteString(ruleViolation.Rule.Identifier) sb.WriteString(":[") for j, v := range ruleViolation.Violations { if j > 0 { sb.WriteByte(',') } sb.WriteString(v.Code) } sb.WriteString("]") } log.Ctx(ctx).Info().Msgf("aborting pull request merge because of rule violations: %s", sb.String()) return nil, &types.MergeViolations{ RuleViolations: violations, Message: protection.GenerateErrorMessageForBlockingViolations(violations), }, nil } // commit details: author, committer and message var author *git.Identity switch in.Method { case enum.MergeMethodMerge: author = controller.IdentityFromPrincipalInfo(*session.Principal.ToPrincipalInfo()) case enum.MergeMethodSquash: author = controller.IdentityFromPrincipalInfo(pr.Author) case enum.MergeMethodRebase, enum.MergeMethodFastForward: author = nil // Not important for these merge methods: the author info in the commits will be preserved. } var committer *git.Identity switch in.Method { case enum.MergeMethodMerge, enum.MergeMethodSquash: committer = controller.SystemServicePrincipalInfo() case enum.MergeMethodRebase: committer = controller.IdentityFromPrincipalInfo(*session.Principal.ToPrincipalInfo()) case enum.MergeMethodFastForward: committer = nil // Not important for fast-forward merge } // backfill commit title if none provided if in.Title == "" { switch in.Method { case enum.MergeMethodMerge: if sourceRepo == nil { in.Title = fmt.Sprintf("Merge branch '%s' of deleted fork (#%d)", pr.SourceBranch, pr.Number) } else { in.Title = fmt.Sprintf("Merge branch '%s' of %s (#%d)", pr.SourceBranch, sourceRepo.Path, pr.Number) } case enum.MergeMethodSquash: in.Title = fmt.Sprintf("%s (#%d)", pr.Title, pr.Number) case enum.MergeMethodRebase, enum.MergeMethodFastForward: // Not used. } } // create merge commit(s) log.Ctx(ctx).Debug().Msgf("all pre-check passed, merge PR") sourceBranchSHA, err := sha.New(in.SourceSHA) if err != nil { return nil, nil, fmt.Errorf("failed to convert source SHA: %w", err) } refTargetBranch, err := git.GetRefPath(pr.TargetBranch, gitenum.RefTypeBranch) if err != nil { return nil, nil, fmt.Errorf("failed to generate target branch ref name: %w", err) } prNumber := strconv.FormatInt(pr.Number, 10) refPullReqHead, err := git.GetRefPath(prNumber, gitenum.RefTypePullReqHead) if err != nil { return nil, nil, fmt.Errorf("failed to generate pull request head ref name: %w", err) } refPullReqMerge, err := git.GetRefPath(prNumber, gitenum.RefTypePullReqMerge) if err != nil { return nil, nil, fmt.Errorf("failed to generate pull requert merge ref name: %w", err) } refUpdates := make([]git.RefUpdate, 0, 4) // Update the target branch to the result of the merge. refUpdates = append(refUpdates, git.RefUpdate{ Name: refTargetBranch, Old: targetSHA, New: sha.SHA{}, // update to the result of the merge. }) // Make sure the PR head ref points to the correct commit after the merge. refUpdates = append(refUpdates, git.RefUpdate{ Name: refPullReqHead, Old: sha.SHA{}, // don't care about the old value. New: sourceBranchSHA, }) // Delete the PR merge reference. refUpdates = append(refUpdates, git.RefUpdate{ Name: refPullReqMerge, Old: sha.SHA{}, New: sha.Nil, }) now := time.Now() mergeOutput, err := c.git.Merge(ctx, &git.MergeParams{ WriteParams: targetWriteParams, BaseSHA: targetSHA, HeadSHA: sourceSHA, Message: git.CommitMessage(in.Title, in.Message), Committer: committer, CommitterDate: &now, Author: author, AuthorDate: &now, Refs: refUpdates, Method: gitenum.MergeMethod(in.Method), }) if errors.IsInvalidArgument(err) || gitapi.IsUnrelatedHistoriesError(err) { inClose := pullreq.NonUniqueMergeBaseInput{ PullReqStore: c.pullreqStore, ActivityStore: c.activityStore, PullReqEvReporter: c.eventReporter, SSEStreamer: c.sseStreamer, } errClose := pullreq.CloseBecauseNonUniqueMergeBase(ctx, inClose, targetSHA, sourceSHA, pr) if errClose != nil { return nil, nil, fmt.Errorf("failed to close pull request after non-unique merge base: %w", errClose) } return nil, nil, err } if err != nil { return nil, nil, fmt.Errorf("merge execution failed: %w", err) } //nolint:nestif if mergeOutput.MergeSHA.String() == "" || len(mergeOutput.ConflictFiles) > 0 { _, err = c.pullreqStore.UpdateMergeCheckMetadataOptLock(ctx, pr, func(pr *types.PullReq) error { if pr.SourceSHA != mergeOutput.HeadSHA.String() { return errors.New("source SHA has changed") } // update all Merge specific information pr.MergeBaseSHA = mergeOutput.MergeBaseSHA.String() pr.MergeTargetSHA = ptr.String(mergeOutput.BaseSHA.String()) pr.MergeSHA = nil pr.UpdateMergeOutcome(in.Method, mergeOutput.ConflictFiles) pr.Stats.DiffStats = types.NewDiffStats( mergeOutput.CommitCount, mergeOutput.ChangedFileCount, mergeOutput.Additions, mergeOutput.Deletions, ) return nil }) if err != nil { // non-critical error log.Ctx(ctx).Warn().Err(err).Msg("failed to update pull request with conflict files") } else { c.sseStreamer.Publish(ctx, targetRepo.ParentID, enum.SSETypePullReqUpdated, pr) } log.Ctx(ctx).Info().Msg("aborting pull request merge because of conflicts") return nil, &types.MergeViolations{ ConflictFiles: mergeOutput.ConflictFiles, RuleViolations: violations, // In case of conflicting files we prioritize those for the error message. Message: fmt.Sprintf("Merge blocked by conflicting files: %v", mergeOutput.ConflictFiles), }, nil } log.Ctx(ctx).Debug().Msgf("successfully merged PR") mergedBy := session.Principal.ID var activitySeqMerge, activitySeqBranchDeleted int64 pr, err = c.pullreqStore.UpdateOptLock(ctx, pr, func(pr *types.PullReq) error { pr.State = enum.PullReqStateMerged nowMilli := now.UnixMilli() pr.Merged = &nowMilli pr.MergedBy = &mergedBy pr.MergeMethod = &in.Method // update all Merge specific information (might be empty if previous merge check failed) // since this is the final operation on the PR, we update any sha that might've changed by now. pr.SourceSHA = mergeOutput.HeadSHA.String() pr.MergeTargetSHA = ptr.String(mergeOutput.BaseSHA.String()) pr.MergeBaseSHA = mergeOutput.MergeBaseSHA.String() pr.MergeSHA = ptr.String(mergeOutput.MergeSHA.String()) pr.MarkAsMerged() bypassed := protection.IsBypassed(violations) pr.MergeViolationsBypassed = &bypassed pr.Stats.DiffStats = types.NewDiffStats( mergeOutput.CommitCount, mergeOutput.ChangedFileCount, mergeOutput.Additions, mergeOutput.Deletions, ) // update sequence for PR activities pr.ActivitySeq++ activitySeqMerge = pr.ActivitySeq if deleteSourceBranch { pr.ActivitySeq++ activitySeqBranchDeleted = pr.ActivitySeq } return nil }) if err != nil { return nil, nil, fmt.Errorf("failed to update pull request: %w", err) } pr.ActivitySeq = activitySeqMerge activityPayload := &types.PullRequestActivityPayloadMerge{ MergeMethod: in.Method, MergeSHA: mergeOutput.MergeSHA.String(), TargetSHA: mergeOutput.BaseSHA.String(), SourceSHA: mergeOutput.HeadSHA.String(), RulesBypassed: protection.IsBypassed(violations), } if _, errAct := c.activityStore.CreateWithPayload(ctx, pr, mergedBy, activityPayload, nil); errAct != nil { // non-critical error log.Ctx(ctx).Err(errAct).Msgf("failed to write pull req merge activity") } c.eventReporter.Merged(ctx, &pullreqevents.MergedPayload{ Base: eventBase(pr, &session.Principal), MergeMethod: in.Method, MergeSHA: mergeOutput.MergeSHA.String(), TargetSHA: mergeOutput.BaseSHA.String(), SourceSHA: mergeOutput.HeadSHA.String(), }) var branchDeleted bool if deleteSourceBranch { errDelete := c.git.DeleteBranch(ctx, &git.DeleteBranchParams{ WriteParams: sourceWriteParams, BranchName: pr.SourceBranch, }) if errDelete != nil { // non-critical error log.Ctx(ctx).Err(errDelete).Msgf("failed to delete source branch after merging") } else { branchDeleted = true // NOTE: there is a chance someone pushed on the branch between merge and delete. // Either way, we'll use the SHA that was merged with for the activity to be consistent from PR perspective. pr.ActivitySeq = activitySeqBranchDeleted if _, errAct := c.activityStore.CreateWithPayload(ctx, pr, mergedBy, &types.PullRequestActivityPayloadBranchDelete{SHA: in.SourceSHA}, nil); errAct != nil { // non-critical error log.Ctx(ctx).Err(errAct). Msgf("failed to write pull request activity for successful automatic branch delete") } } } c.sseStreamer.Publish(ctx, targetRepo.ParentID, enum.SSETypePullReqUpdated, pr) if protection.IsBypassed(violations) { err = c.auditService.Log(ctx, session.Principal, audit.NewResource( audit.ResourceTypeRepository, targetRepo.Identifier, audit.RepoPath, targetRepo.Path, audit.BypassedResourceType, audit.BypassedResourceTypePullRequest, audit.BypassedResourceName, strconv.FormatInt(pr.Number, 10), audit.ResourceName, fmt.Sprintf( audit.BypassPullReqLabelFormat, targetRepo.Identifier, strconv.FormatInt(pr.Number, 10), ), audit.BypassAction, audit.BypassActionMerged, ), audit.ActionBypassed, paths.Parent(targetRepo.Path), audit.WithNewObject(audit.PullRequestObject{ PullReq: *pr, RepoPath: targetRepo.Path, RuleViolations: violations, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for merge pull request operation: %s", err) } } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeMergePullRequest, Principal: session.Principal.ToPrincipalInfo(), Path: targetRepo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: targetRepo.ID, instrument.PropertyRepositoryName: targetRepo.Identifier, instrument.PropertyPullRequestID: pr.Number, instrument.PropertyMergeStrategy: in.Method, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for merge pr operation: %s", err) } return &types.MergeResponse{ SHA: mergeOutput.MergeSHA.String(), BranchDeleted: branchDeleted, RuleViolations: violations, }, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/label_assign.go
app/api/controller/pullreq/label_assign.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/auth" events "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/services/label" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // AssignLabel assigns a label to a pull request . func (c *Controller) AssignLabel( ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, in *types.PullReqLabelAssignInput, ) (*types.PullReqLabel, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return nil, fmt.Errorf("failed to acquire access to target repo: %w", err) } if err := in.Validate(); err != nil { return nil, fmt.Errorf("failed to validate input: %w", err) } pullreq, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return nil, fmt.Errorf("failed to find pullreq: %w", err) } out, err := c.labelSvc.AssignToPullReq( ctx, session.Principal.ID, pullreq.ID, repo.ID, repo.ParentID, in) if err != nil { return nil, fmt.Errorf("failed to create pullreq label: %w", err) } if out.ActivityType == enum.LabelActivityNoop { return out.PullReqLabel, nil } pullreq, err = c.pullreqStore.UpdateActivitySeq(ctx, pullreq) if err != nil { return nil, fmt.Errorf("failed to update pull request activity sequence: %w", err) } payload := activityPayload(out) if _, err := c.activityStore.CreateWithPayload( ctx, pullreq, session.Principal.ID, payload, nil); err != nil { log.Ctx(ctx).Err(err).Msg("failed to write pull request activity after label assign") } // if the label has no value, the newValueID will be nil var newValueID *int64 if out.NewLabelValue != nil { newValueID = &out.NewLabelValue.ID } c.eventReporter.LabelAssigned(ctx, &events.LabelAssignedPayload{ Base: events.Base{ PullReqID: pullreq.ID, SourceRepoID: pullreq.SourceRepoID, TargetRepoID: pullreq.TargetRepoID, PrincipalID: session.Principal.ID, Number: pullreq.Number, }, LabelID: out.Label.ID, ValueID: newValueID, }) return out.PullReqLabel, nil } func activityPayload(out *label.AssignToPullReqOut) *types.PullRequestActivityLabel { var oldValue *string var oldValueColor *enum.LabelColor if out.OldLabelValue != nil { oldValue = &out.OldLabelValue.Value oldValueColor = &out.OldLabelValue.Color } var value *string var valueColor *enum.LabelColor if out.NewLabelValue != nil { value = &out.NewLabelValue.Value valueColor = &out.NewLabelValue.Color } return &types.PullRequestActivityLabel{ PullRequestActivityLabelBase: types.PullRequestActivityLabelBase{ Label: out.Label.Key, LabelColor: out.Label.Color, LabelScope: out.Label.Scope, Value: value, ValueColor: valueColor, OldValue: oldValue, OldValueColor: oldValueColor, }, Type: out.ActivityType, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/wire.go
app/api/controller/pullreq/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 pullreq import ( "github.com/harness/gitness/app/auth/authz" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/services/codecomments" "github.com/harness/gitness/app/services/codeowners" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/label" "github.com/harness/gitness/app/services/locker" "github.com/harness/gitness/app/services/migrate" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/app/services/pullreq" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/services/usergroup" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/audit" "github.com/harness/gitness/git" "github.com/harness/gitness/store/database/dbtx" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideController, ) func ProvideController( tx dbtx.Transactor, urlProvider url.Provider, authorizer authz.Authorizer, auditService audit.Service, pullReqStore store.PullReqStore, pullReqActivityStore store.PullReqActivityStore, codeCommentsView store.CodeCommentView, pullReqReviewStore store.PullReqReviewStore, pullReqReviewerStore store.PullReqReviewerStore, repoStore store.RepoStore, principalStore store.PrincipalStore, userGroupStore store.UserGroupStore, userGroupReviewerStore store.UserGroupReviewerStore, principalInfoCache store.PrincipalInfoCache, fileViewStore store.PullReqFileViewStore, membershipStore store.MembershipStore, checkStore store.CheckStore, rpcClient git.Interface, repoFinder refcache.RepoFinder, eventReporter *pullreqevents.Reporter, codeCommentMigrator *codecomments.Migrator, pullreqService *pullreq.Service, pullreqListService *pullreq.ListService, ruleManager *protection.Manager, sseStreamer sse.Streamer, codeOwners *codeowners.Service, locker *locker.Locker, importer *migrate.PullReq, labelSvc *label.Service, instrumentation instrument.Service, userGroupService usergroup.Service, branchStore store.BranchStore, userGroupResolver usergroup.Resolver, ) *Controller { return NewController(tx, urlProvider, authorizer, auditService, pullReqStore, pullReqActivityStore, codeCommentsView, pullReqReviewStore, pullReqReviewerStore, repoStore, principalStore, userGroupStore, userGroupReviewerStore, principalInfoCache, fileViewStore, membershipStore, checkStore, rpcClient, repoFinder, eventReporter, codeCommentMigrator, pullreqService, pullreqListService, ruleManager, sseStreamer, codeOwners, locker, importer, labelSvc, instrumentation, userGroupService, branchStore, userGroupResolver, ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/branch_change_target.go
app/api/controller/pullreq/branch_change_target.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" gitenum "github.com/harness/gitness/git/enum" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/gotidy/ptr" "github.com/rs/zerolog/log" ) type ChangeTargetBranchInput struct { BranchName string `json:"branch_name"` } func (c *Controller) ChangeTargetBranch(ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, in *ChangeTargetBranchInput, ) (*types.PullReq, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return nil, fmt.Errorf("failed to get pull request by number: %w", err) } if pr.State == enum.PullReqSortMerged { return nil, errors.InvalidArgument("Pull request is already merged.") } if _, err = c.verifyBranchExistence(ctx, repo, in.BranchName); err != nil { return nil, fmt.Errorf("failed to verify branch existence: %w", err) } if pr.TargetBranch == in.BranchName { return pr, nil } if pr.SourceRepoID != nil && pr.TargetRepoID == *pr.SourceRepoID && pr.SourceBranch == in.BranchName { return nil, errors.InvalidArgumentf("Source branch %q is same as new target branch", pr.SourceBranch) } readParams := git.CreateReadParams(repo) targetRef, err := c.git.GetRef(ctx, git.GetRefParams{ ReadParams: readParams, Name: in.BranchName, Type: gitenum.RefTypeBranch, }) if err != nil { return nil, fmt.Errorf("failed to resolve target branch reference: %w", err) } targetSHA := targetRef.SHA mergeBase, err := c.git.MergeBase(ctx, git.MergeBaseParams{ ReadParams: readParams, Ref1: pr.SourceSHA, Ref2: targetSHA.String(), }) if err != nil { return nil, fmt.Errorf("failed to find merge base: %w", err) } if mergeBase.MergeBaseSHA.String() == pr.SourceSHA { return nil, usererror.BadRequest("The source branch doesn't contain any new commits") } diffStats, err := c.git.DiffStats(ctx, &git.DiffParams{ ReadParams: readParams, BaseRef: pr.MergeBaseSHA, HeadRef: pr.SourceSHA, }) if err != nil { return nil, fmt.Errorf("failed get diff stats: %w", err) } oldTargetBranch := pr.TargetBranch oldMergeBaseSHA := pr.MergeBaseSHA pr, err = c.pullreqStore.UpdateOptLock(ctx, pr, func(pr *types.PullReq) error { pr.MergeSHA = nil pr.MarkAsMergeUnchecked() pr.MergeBaseSHA = mergeBase.MergeBaseSHA.String() pr.MergeTargetSHA = ptr.String(targetSHA.String()) pr.TargetBranch = in.BranchName pr.Stats.DiffStats = types.NewDiffStats( diffStats.Commits, diffStats.FilesChanged, diffStats.Additions, diffStats.Deletions, ) pr.ActivitySeq++ return nil }) if err != nil { return nil, fmt.Errorf("failed to update PR target branch in db with error: %w", err) } _, err = c.activityStore.CreateWithPayload( ctx, pr, session.Principal.ID, &types.PullRequestActivityPayloadBranchChangeTarget{ Old: oldTargetBranch, New: in.BranchName, }, nil, ) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to write pull request activity for successful branch restore") } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeChangeTargetBranch, Principal: session.Principal.ToPrincipalInfo(), Path: repo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, instrument.PropertyTargetBranch: in.BranchName, instrument.PropertyPullRequestID: pr.Number, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for create branch operation: %s", err) } c.eventReporter.TargetBranchChanged(ctx, &pullreqevents.TargetBranchChangedPayload{ Base: eventBase(pr, &session.Principal), SourceSHA: pr.SourceSHA, OldTargetBranch: oldTargetBranch, NewTargetBranch: in.BranchName, OldMergeBaseSHA: oldMergeBaseSHA, NewMergeBaseSHA: mergeBase.MergeBaseSHA.String(), }) return pr, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/comment_status.go
app/api/controller/pullreq/comment_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 pullreq import ( "context" "fmt" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" events "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type CommentStatusInput struct { Status enum.PullReqCommentStatus `json:"status"` } func (in *CommentStatusInput) Validate() error { _, ok := in.Status.Sanitize() if !ok { return usererror.BadRequest("Invalid value provided for comment status") } return nil } func (in *CommentStatusInput) hasChanges(act *types.PullReqActivity, userID int64) bool { // clearing resolved if in.Status == enum.PullReqCommentStatusActive { return act.Resolved != nil } // setting resolved return act.Resolved == nil || act.ResolvedBy == nil || *act.ResolvedBy != userID } // CommentStatus updates a pull request comment status. func (c *Controller) CommentStatus( ctx context.Context, session *auth.Session, repoRef string, prNum int64, commentID int64, in *CommentStatusInput, ) (*types.PullReqActivity, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } var pr *types.PullReq var act *types.PullReqActivity err = controller.TxOptLock(ctx, c.tx, func(ctx context.Context) error { pr, err = c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return fmt.Errorf("failed to find pull request by number: %w", err) } if errValidate := in.Validate(); errValidate != nil { return errValidate } act, err = c.getCommentCheckChangeStatusAccess(ctx, pr, commentID) if err != nil { return fmt.Errorf("failed to get comment: %w", err) } if !in.hasChanges(act, session.Principal.ID) { return nil } act.Resolved = nil act.ResolvedBy = nil now := time.Now().UnixMilli() if in.Status != enum.PullReqCommentStatusActive { // In the future if we add more comment resolved statuses // we'll add the ResolvedReason field and put the reason there. // For now, the nullable timestamp field/db-column "Resolved" tells the status (active/resolved). act.Resolved = &now act.ResolvedBy = &session.Principal.ID } err = c.activityStore.Update(ctx, act) if err != nil { return fmt.Errorf("failed to update status of pull request activity: %w", err) } // Here we deliberately use the transaction and counting the unresolved comments, // rather than optimistic locking and incrementing/decrementing the counter. // The idea is that if the counter ever goes out of sync, this would be the place where we get it back in sync. unresolvedCount, err := c.activityStore.CountUnresolved(ctx, pr.ID) if err != nil { return fmt.Errorf("failed to count unresolved comments: %w", err) } pr.UnresolvedCount = unresolvedCount err = c.pullreqStore.Update(ctx, pr) if err != nil { return fmt.Errorf("failed to update pull request's unresolved comment count: %w", err) } return nil }) if err != nil { return nil, err } c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypePullReqUpdated, pr) c.eventReporter.CommentStatusUpdated(ctx, &events.CommentStatusUpdatedPayload{ Base: events.Base{ PullReqID: pr.ID, SourceRepoID: pr.SourceRepoID, TargetRepoID: pr.TargetRepoID, PrincipalID: session.Principal.ID, Number: pr.Number, }, ActivityID: act.ID, }) return act, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/comment_delete.go
app/api/controller/pullreq/comment_delete.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 pullreq import ( "context" "fmt" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // CommentDelete deletes a pull request comment. func (c *Controller) CommentDelete( ctx context.Context, session *auth.Session, repoRef string, prNum int64, commentID int64, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return fmt.Errorf("failed to acquire access to repo: %w", err) } var pr *types.PullReq err = controller.TxOptLock(ctx, c.tx, func(ctx context.Context) error { var err error pr, err = c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return fmt.Errorf("failed to find pull request by number: %w", err) } act, err := c.getCommentCheckEditAccess(ctx, session, pr, commentID) if err != nil { return fmt.Errorf("failed to get comment: %w", err) } if act.Deleted != nil { return nil } now := time.Now().UnixMilli() isBlocking := act.IsBlocking() act.Deleted = &now err = c.activityStore.Update(ctx, act) if err != nil { return fmt.Errorf("failed to mark comment as deleted: %w", err) } pr.CommentCount-- if isBlocking { pr.UnresolvedCount-- } err = c.pullreqStore.Update(ctx, pr) if err != nil { return fmt.Errorf("failed to decrement pull request comment counters: %w", err) } return nil }) if err != nil { return err } c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypePullReqUpdated, pr) return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/reviewer_combined_list.go
app/api/controller/pullreq/reviewer_combined_list.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 pullreq import ( "context" "errors" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type CombinedListResponse struct { Reviewers []*types.PullReqReviewer `json:"reviewers,omitempty"` UserGroupReviewers []*types.UserGroupReviewer `json:"user_group_reviewers,omitempty"` } // ReviewersListCombined returns the combined reviewer list for the pull request. func (c *Controller) ReviewersListCombined( ctx context.Context, session *auth.Session, repoRef string, prNum int64, ) (*CombinedListResponse, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return nil, fmt.Errorf("failed to find pull request by number: %w", err) } reviewers, err := c.reviewerStore.List(ctx, pr.ID) if err != nil { return nil, fmt.Errorf("failed to list reviewers: %w", err) } userGroupReviewers, err := c.userGroupReviewerStore.List(ctx, pr.ID) if err != nil && !errors.Is(err, store.ErrResourceNotFound) { return nil, fmt.Errorf("failed to list user group reviewers: %w", err) } if errors.Is(err, store.ErrResourceNotFound) || len(userGroupReviewers) == 0 { return &CombinedListResponse{ Reviewers: reviewers, }, nil } userGroupReviewersMap := make(map[int64]*types.UserGroupReviewer, len(userGroupReviewers)) for _, userGroupReviewer := range userGroupReviewers { userGroupReviewersMap[userGroupReviewer.UserGroupID] = userGroupReviewer } addedByIDs := make([]int64, len(userGroupReviewers)) userGroupIDs := make([]int64, len(userGroupReviewers)) for i, v := range userGroupReviewers { addedByIDs[i] = v.CreatedBy userGroupIDs[i] = v.UserGroupID } userGroupsMap, err := c.userGroupStore.Map(ctx, userGroupIDs) if err != nil { return nil, fmt.Errorf("failed to map usergroups: %w", err) } principalInfoCacheMap, err := c.principalInfoCache.Map(ctx, addedByIDs) if err != nil { return nil, fmt.Errorf("failed to load PR principal infos: %w", err) } groupPrincipalsMap, err := c.userGroupService.MapGroupIDsToPrincipals(ctx, userGroupIDs) if err != nil { return nil, fmt.Errorf("failed to map group IDs to principals: %w", err) } reviewersMap := reviewersMap(reviewers) for groupID, principals := range groupPrincipalsMap { // userGroupReviewersMap, userGroupsMap and groupPrincipalsMap depend on userGroupReviewers // if a group doesn't exist in userGroupReviewers it won't exist in any of these // and if it exists in userGroupReviewers it will exist in all of these userGroupReviewer := userGroupReviewersMap[groupID] userGroupReviewer.UserGroup = *userGroupsMap[groupID].ToUserGroupInfo() // principal could be deleted/removed without group being, so we check for its existence if addedBy, ok := principalInfoCacheMap[userGroupReviewer.CreatedBy]; ok { userGroupReviewer.AddedBy = *addedBy } // compound user group decision userGroupReviewer.Decision = enum.PullReqReviewDecisionPending userGroupReviewer.SHA = "" // individual decisions of the principals in the group var principalIDs []int64 for _, principal := range principals { principalIDs = append(principalIDs, principal.ID) } userGroupReviewerDecisions := userGroupReviewerDecisions(principalIDs, reviewersMap) userGroupReviewer.UserDecisions = userGroupReviewerDecisions userGroupReviewer.Decision, userGroupReviewer.SHA = determineUserGroupCompoundDecision( userGroupReviewerDecisions, pr.SourceSHA, ) } return &CombinedListResponse{ Reviewers: reviewers, UserGroupReviewers: userGroupReviewers, }, nil } // userGroupReviewerDecisions builds a slice of ReviewerEvaluation from user IDs and reviewers map. func userGroupReviewerDecisions( userIDs []int64, reviewersMap map[int64]*types.PullReqReviewer, ) []types.ReviewerEvaluation { var userGroupReviewerDecisions []types.ReviewerEvaluation for _, userID := range userIDs { reviewer, ok := reviewersMap[userID] if !ok { continue } decision := types.ReviewerEvaluation{ Decision: reviewer.ReviewDecision, SHA: reviewer.SHA, Reviewer: reviewer.Reviewer, Updated: reviewer.Updated, } userGroupReviewerDecisions = append(userGroupReviewerDecisions, decision) } return userGroupReviewerDecisions } // determineUserGroupCompoundDecision determines the compound decision and SHA for a user group reviewer // based on individual reviewer decisions, prioritizing reviews on the source SHA. func determineUserGroupCompoundDecision( userGroupReviewerDecisions []types.ReviewerEvaluation, prSourceSHA string, ) (enum.PullReqReviewDecision, string) { // Separate reviews on source SHA vs other SHAs var latestSHAReviews []types.ReviewerEvaluation var otherSHAReviews []types.ReviewerEvaluation var userGroupSHA string var latestUpdated int64 for _, decision := range userGroupReviewerDecisions { if decision.SHA == prSourceSHA { latestSHAReviews = append(latestSHAReviews, decision) } else { otherSHAReviews = append(otherSHAReviews, decision) // Track the most recently updated reviewer for fallback SHA if decision.Updated > latestUpdated { latestUpdated = decision.Updated userGroupSHA = decision.SHA } } } // If we have source SHA reviews, override userGroupSHA to source SHA if len(latestSHAReviews) > 0 { userGroupSHA = prSourceSHA } // Determine the compound decision: // 1. Prioritize reviews on the source SHA // 2. Apply the highest decision order among those reviews // 3. If no reviews on source SHA, use the highest order from other SHAs var decisionsToConsider []types.ReviewerEvaluation if len(latestSHAReviews) > 0 { decisionsToConsider = latestSHAReviews } else { decisionsToConsider = otherSHAReviews } decision := enum.PullReqReviewDecisionPending for _, reviewDecision := range decisionsToConsider { decision = getHighestOrderDecision(decision, reviewDecision.Decision) } return decision, userGroupSHA } func getHighestOrderDecision( d1 enum.PullReqReviewDecision, d2 enum.PullReqReviewDecision, ) enum.PullReqReviewDecision { if d1 == enum.PullReqReviewDecisionChangeReq || d2 == enum.PullReqReviewDecisionChangeReq { return enum.PullReqReviewDecisionChangeReq } if d1 == enum.PullReqReviewDecisionApproved || d2 == enum.PullReqReviewDecisionApproved { return enum.PullReqReviewDecisionApproved } if d1 == enum.PullReqReviewDecisionReviewed || d2 == enum.PullReqReviewDecisionReviewed { return enum.PullReqReviewDecisionReviewed } return enum.PullReqReviewDecisionPending }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/revert.go
app/api/controller/pullreq/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 pullreq import ( "context" "fmt" "strconv" "strings" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type RevertInput struct { Title string `json:"title"` Message string `json:"message"` // RevertBranch is the name of new branch that will be created on which the revert commit will be put. // It's optional, if no value has been provided the default ("revert-pullreq-<number>") would be used. RevertBranch string `json:"revert_branch"` } func (in *RevertInput) sanitize() { in.Title = strings.TrimSpace(in.Title) in.Message = strings.TrimSpace(in.Message) in.RevertBranch = strings.TrimSpace(in.RevertBranch) } func (c *Controller) Revert( ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, in *RevertInput, ) (*types.RevertResponse, error) { in.sanitize() repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } if pr.State != enum.PullReqStateMerged { return nil, usererror.BadRequest("Only merged pull requests can be reverted.") } readParams := git.CreateReadParams(repo) writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return nil, fmt.Errorf("failed to create RPC write params: %w", err) } revertBranch := in.RevertBranch if revertBranch == "" { revertBranch = "revert-pullreq-" + strconv.FormatInt(pullreqNum, 10) } _, err = c.git.GetBranch(ctx, &git.GetBranchParams{ ReadParams: readParams, BranchName: revertBranch, }) if err != nil && !errors.IsNotFound(err) { return nil, fmt.Errorf("failed to get revert branch: %w", err) } if err == nil { return nil, errors.InvalidArgumentf("Branch %q already exists.", revertBranch) } title := in.Title message := in.Message if title == "" { title = fmt.Sprintf("Revert Pull Request #%d %q", pullreqNum, pr.Title) } commitMessage := git.CommitMessage(title, message) author := controller.IdentityFromPrincipalInfo(*session.Principal.ToPrincipalInfo()) committer := controller.SystemServicePrincipalInfo() now := time.Now() result, err := c.git.Revert(ctx, &git.RevertParams{ WriteParams: writeParams, ParentCommitSHA: sha.Must(*pr.MergeSHA), FromCommitSHA: sha.Must(pr.MergeBaseSHA), ToCommitSHA: sha.Must(pr.SourceSHA), RevertBranch: revertBranch, Message: commitMessage, Committer: committer, CommitterDate: &now, Author: author, AuthorDate: &now, }) if err != nil { return nil, fmt.Errorf("failed to revert pull request: %w", err) } gitCommit, err := c.git.GetCommit(ctx, &git.GetCommitParams{ ReadParams: readParams, Revision: result.CommitSHA.String(), }) if err != nil { return nil, fmt.Errorf("failed to get revert commit: %w", err) } return &types.RevertResponse{ Branch: revertBranch, Commit: *controller.MapCommit(&gitCommit.Commit), }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/reviewer_add.go
app/api/controller/pullreq/reviewer_add.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 pullreq import ( "context" "errors" "fmt" "time" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" events "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type ReviewerAddInput struct { ReviewerID int64 `json:"reviewer_id"` } // ReviewerAdd adds a new reviewer to the pull request. func (c *Controller) ReviewerAdd( ctx context.Context, session *auth.Session, repoRef string, prNum int64, in *ReviewerAddInput, ) (*types.PullReqReviewer, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return nil, fmt.Errorf("failed to find pull request by number: %w", err) } if pr.Merged != nil { return nil, usererror.BadRequest("Can't request review for merged pull request") } if in.ReviewerID == 0 { return nil, usererror.BadRequest("Must specify reviewer ID.") } if in.ReviewerID == pr.CreatedBy { return nil, usererror.BadRequest("Pull request author can't be added as a reviewer.") } addedByInfo := session.Principal.ToPrincipalInfo() var reviewerType enum.PullReqReviewerType switch session.Principal.ID { case pr.CreatedBy: reviewerType = enum.PullReqReviewerTypeRequested case in.ReviewerID: reviewerType = enum.PullReqReviewerTypeSelfAssigned default: reviewerType = enum.PullReqReviewerTypeAssigned } reviewerInfo := addedByInfo if reviewerType != enum.PullReqReviewerTypeSelfAssigned { var reviewerPrincipal *types.Principal reviewerPrincipal, err = c.principalStore.Find(ctx, in.ReviewerID) if err != nil { return nil, fmt.Errorf("failed to find reviewer principal: %w", err) } reviewerInfo = reviewerPrincipal.ToPrincipalInfo() // TODO: To check the reviewer's access to the repo we create a dummy session object. Fix it. if err = apiauth.CheckRepo(ctx, c.authorizer, &auth.Session{ Principal: *reviewerPrincipal, Metadata: nil, }, repo, enum.PermissionRepoReview); err != nil { log.Ctx(ctx).Info().Msgf("Reviewer principal: %s access error: %s", reviewerInfo.UID, err) return nil, usererror.BadRequest("The reviewer doesn't have enough permissions for the repository.") } } var reviewer *types.PullReqReviewer var added bool err = c.tx.WithTx(ctx, func(ctx context.Context) error { reviewer, err = c.reviewerStore.Find(ctx, pr.ID, in.ReviewerID) if err != nil && !errors.Is(err, store.ErrResourceNotFound) { return err } if reviewer != nil { return nil } reviewer = newPullReqReviewer(session, pr, repo, reviewerInfo, addedByInfo, reviewerType, in) added = true return c.reviewerStore.Create(ctx, reviewer) }) if err != nil { return nil, fmt.Errorf("failed to create pull request reviewer: %w", err) } if !added { return reviewer, nil } err = func() error { payload := &types.PullRequestActivityPayloadReviewerAdd{ PrincipalID: reviewer.PrincipalID, ReviewerType: reviewerType, } metadata := &types.PullReqActivityMetadata{ Mentions: &types.PullReqActivityMentionsMetadata{IDs: []int64{reviewer.PrincipalID}}, } if pr, err = c.pullreqStore.UpdateActivitySeq(ctx, pr); err != nil { return fmt.Errorf("failed to increment pull request activity sequence: %w", err) } _, err = c.activityStore.CreateWithPayload(ctx, pr, session.Principal.ID, payload, metadata) if err != nil { return fmt.Errorf("failed to create pull request activity: %w", err) } return nil }() if err != nil { log.Ctx(ctx).Err(err).Msg("failed to write pull request activity after adding a reviewer") } c.reportReviewerAddition(ctx, session, pr, reviewer) c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypePullReqReviewerAdded, pr) return reviewer, nil } func (c *Controller) reportReviewerAddition( ctx context.Context, session *auth.Session, pr *types.PullReq, reviewer *types.PullReqReviewer, ) { c.eventReporter.ReviewerAdded(ctx, &events.ReviewerAddedPayload{ Base: eventBase(pr, &session.Principal), ReviewerID: reviewer.PrincipalID, }) } // newPullReqReviewer creates new pull request reviewer object. func newPullReqReviewer( session *auth.Session, pullReq *types.PullReq, repo *types.RepositoryCore, reviewerInfo, addedByInfo *types.PrincipalInfo, reviewerType enum.PullReqReviewerType, in *ReviewerAddInput, ) *types.PullReqReviewer { now := time.Now().UnixMilli() return &types.PullReqReviewer{ PullReqID: pullReq.ID, PrincipalID: in.ReviewerID, CreatedBy: session.Principal.ID, Created: now, Updated: now, RepoID: repo.ID, Type: reviewerType, LatestReviewID: nil, ReviewDecision: enum.PullReqReviewDecisionPending, SHA: "", Reviewer: *reviewerInfo, AddedBy: *addedByInfo, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/mentions.go
app/api/controller/pullreq/mentions.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 pullreq import ( "context" "fmt" "regexp" "strconv" "github.com/harness/gitness/types" "github.com/rs/zerolog/log" ) func (c *Controller) processMentions( ctx context.Context, text string, ) (map[int64]*types.PrincipalInfo, error) { mentions := parseMentions(ctx, text) if len(mentions) == 0 { return map[int64]*types.PrincipalInfo{}, nil } infos, err := c.principalInfoCache.Map(ctx, mentions) if err != nil { return nil, fmt.Errorf("failed to fetch info from principalInfoCache: %w", err) } return infos, nil } var mentionRegex = regexp.MustCompile(`@\[(\d+)\]`) func parseMentions(ctx context.Context, text string) []int64 { matches := mentionRegex.FindAllStringSubmatch(text, -1) var mentions []int64 for _, match := range matches { if len(match) < 2 { continue } if mention, err := strconv.ParseInt(match[1], 10, 64); err == nil { mentions = append(mentions, mention) } else { log.Ctx(ctx).Warn().Err(err).Msgf("failed to parse mention %q", match[1]) } } return mentions }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/file_view_add.go
app/api/controller/pullreq/file_view_add.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 pullreq import ( "context" "fmt" "time" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type FileViewAddInput struct { Path string `json:"path"` CommitSHA string `json:"commit_sha"` } func (f *FileViewAddInput) Validate() error { if f.Path == "" { return usererror.BadRequest("Path can't be empty") } if !git.ValidateCommitSHA(f.CommitSHA) { return usererror.BadRequest("Commit SHA is invalid") } return nil } // FileViewAdd marks a file as viewed. // NOTE: // We take the commit SHA from the user to ensure we mark as viewed only what the user actually sees. // The downside is that the caller could provide a SHA that never was part of the PR in the first place. // We can't block against that with our current data, as the existence of force push makes it impossible to verify // whether the commit ever was part of the PR - it would require us to store the full pr.SourceSHA history. // //nolint:gocognit // refactor if needed. func (c *Controller) FileViewAdd( ctx context.Context, session *auth.Session, repoRef string, prNum int64, in *FileViewAddInput, ) (*types.PullReqFileView, error) { if err := in.Validate(); err != nil { return nil, err } repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return nil, fmt.Errorf("failed to find pull request by number: %w", err) } // retrieve file from both provided SHA and mergeBaseSHA to validate user input inNode, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{ ReadParams: git.CreateReadParams(repo), GitREF: in.CommitSHA, Path: in.Path, IncludeLatestCommit: false, }) if err != nil && !errors.IsNotFound(err) { return nil, fmt.Errorf( "failed to get tree node '%s' for provided sha '%s': %w", in.Path, in.CommitSHA, err, ) } // ensure provided path actually points to a blob or commit (submodule) if inNode != nil && inNode.Node.Type != git.TreeNodeTypeBlob && inNode.Node.Type != git.TreeNodeTypeCommit { return nil, usererror.BadRequestf("Provided path '%s' doesn't point to a file.", in.Path) } mergeBaseNode, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{ ReadParams: git.CreateReadParams(repo), GitREF: pr.MergeBaseSHA, Path: in.Path, IncludeLatestCommit: false, }) if err != nil && !errors.IsNotFound(err) { return nil, fmt.Errorf( "failed to get tree node '%s' for MergeBaseSHA '%s': %w", in.Path, pr.MergeBaseSHA, err, ) } // fail the call in case the file doesn't exist in either, or in case it didn't change. // NOTE: There is a RARE chance if the user provides an old SHA AND there's a new mergeBaseSHA // which now already contains the changes, that we return an error saying there are no changes // (even though with the old merge base there were). Effectively, it would lead to the users // 'file viewed' resetting when the user refreshes the page - we are okay with that. if inNode == nil && mergeBaseNode == nil { return nil, usererror.BadRequestf( "File '%s' neither found for merge-base '%s' nor for provided sha '%s'.", in.Path, pr.MergeBaseSHA, in.CommitSHA, ) } if inNode != nil && mergeBaseNode != nil && inNode.Node.SHA == mergeBaseNode.Node.SHA { return nil, usererror.BadRequestf( "File '%s' is not part of changes between merge-base '%s' and provided sha '%s'.", in.Path, pr.MergeBaseSHA, in.CommitSHA, ) } // in case of deleted file set sha to nilsha - that's how git diff treats it, too. sha := types.NilSHA if inNode != nil { sha = inNode.Node.SHA } now := time.Now().UnixMilli() fileView := &types.PullReqFileView{ PullReqID: pr.ID, PrincipalID: session.Principal.ID, Path: in.Path, SHA: sha, // always add as non-obsolete, even if the file view is derived from a non-latest commit sha. // The file sha ensures that the user's review is out of date in case the file changed in the meanwhile. // And in the rare case of the file having changed and changed back between the two commits, // the content the reviewer just approved on is the same, so it's actually good to not mark it as obsolete. Obsolete: false, Created: now, Updated: now, } err = c.fileViewStore.Upsert(ctx, fileView) if err != nil { return nil, fmt.Errorf("failed to upsert file view information in db: %w", err) } return fileView, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/pr_branch_candidates.go
app/api/controller/pullreq/pr_branch_candidates.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 pullreq import ( "context" "fmt" "time" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) const ( PRBannerDuration = 2 * time.Hour PRBannerDefaultLimitForPage = 3 PRBannerMaxLimitForPage = 10 ) // PRBranchCandidates finds branch names updated by the current user that don't have PRs. func (c *Controller) PRBranchCandidates( ctx context.Context, session *auth.Session, repoRef string, limit uint64, ) ([]types.BranchTable, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } cutOffTime := time.Now().Add(-PRBannerDuration) // getting latest sha from db instead of git as pr candidate need not be 100% accurate defaultBranch, err := c.branchStore.Find(ctx, repo.ID, repo.DefaultBranch) if err != nil { return nil, fmt.Errorf("failed to get default branch: %w", err) } branches, err := c.branchStore.FindBranchesWithoutOpenPRs(ctx, repo.ID, session.Principal.ID, cutOffTime.UnixMilli(), limit+1, defaultBranch.SHA.String()) if err != nil { return nil, fmt.Errorf("failed to list branches: %w", err) } // Filter out default branch if present result := make([]types.BranchTable, 0, len(branches)) for _, branch := range branches { if branch.Name != repo.DefaultBranch { result = append(result, branch) } // Stop once we've reached the limit if uint64(len(result)) >= limit { break } } return result, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/file_view_list.go
app/api/controller/pullreq/file_view_list.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // FileViewList lists all files of the PR marked as viewed for the user. func (c *Controller) FileViewList( ctx context.Context, session *auth.Session, repoRef string, prNum int64, ) ([]*types.PullReqFileView, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return nil, fmt.Errorf("failed to find pull request by number: %w", err) } fileViews, err := c.fileViewStore.List(ctx, pr.ID, session.Principal.ID) if err != nil { return nil, fmt.Errorf("failed to read file view entries for user from db: %w", err) } return fileViews, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/reviewer_list.go
app/api/controller/pullreq/reviewer_list.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ReviewerList returns reviewer list for the pull request. func (c *Controller) ReviewerList( ctx context.Context, session *auth.Session, repoRef string, prNum int64, ) ([]*types.PullReqReviewer, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return nil, fmt.Errorf("failed to find pull request by number: %w", err) } reviewers, err := c.reviewerStore.List(ctx, pr.ID) return reviewers, err }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/suggestions.go
app/api/controller/pullreq/suggestions.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 pullreq import ( "crypto/sha256" "fmt" "strings" ) type suggestion struct { checkSum string code string } // parseSuggestions parses the provided string for any markdown code blocks that are suggestions. func parseSuggestions(s string) []suggestion { const languageSuggestion = "suggestion" out := []suggestion{} for len(s) > 0 { code, language, remaining, found := findNextMarkdownCodeBlock(s) // always update s to the remainder s = remaining if !found { break } if !strings.EqualFold(language, languageSuggestion) { continue } out = append(out, suggestion{ checkSum: hashCodeBlock(code), code: code, }, ) } return out } func hashCodeBlock(s string) string { return fmt.Sprintf("%x", sha256.Sum256([]byte(s))) } // findNextMarkdownCodeBlock finds a code block in markdown. // NOTE: In the future we might want to use a proper markdown parser. func findNextMarkdownCodeBlock(s string) (code string, language string, remaining string, found bool) { // find fenced code block header var startSequence string s = foreachLine(s, func(line string) bool { line, ok := trimMarkdownWhitespace(line) if !ok { return true } // try to find start sequence of a fenced code block (```+ or ~~~+) startSequence, line = cutLongestPrefix(line, '~') if len(startSequence) < 3 { startSequence, line = cutLongestPrefix(line, '`') if len(startSequence) < 3 { // no code block prefix found in this line return true } if strings.Contains(line, "`") { // any single tic in the same line breaks a code block ``` opening return true } } language = strings.TrimSpace(line) return false }) if len(startSequence) == 0 { return "", "", "", false } // parse codeBuilder block codeBuilder := strings.Builder{} linesAdded := 0 addLineToCode := func(line string) { // To normalize we: // - always use LF line ending // - strip any line ending from last line // // e.g. "```suggestion\n```" is the same as "```suggestion\n" is the same as "```suggestion" // // This ensures similar result with and without end markers for fenced code blocks, // and gives the user control on adding new lines at the end of the file. if linesAdded > 0 { codeBuilder.WriteByte('\n') } linesAdded++ codeBuilder.WriteString(line) } s = foreachLine(s, func(line string) bool { // keep original line for appending it to code block if required originalLine := line line, ok := trimMarkdownWhitespace(line) if !ok { addLineToCode(originalLine) return true } if !strings.HasPrefix(line, startSequence) { addLineToCode(originalLine) return true } _, line = cutLongestPrefix(line, rune(startSequence[0])) // any higher number of chars as starting sequence works line = strings.TrimSpace(line) // spaces are fine if len(line) > 0 { // end of fenced code block can't contain anything else but spaces addLineToCode(originalLine) return true } return false }) return codeBuilder.String(), language, s, true } // trimMarkdownWhitespace returns the provided line by removing any leading whitespaces. // If the white space makes it an indented code block line, false is returned. func trimMarkdownWhitespace(line string) (string, bool) { // remove any leading spaces prefix, updatedLine := cutLongestPrefix(line, ' ') if len(prefix) >= 4 { // line is considered a code line by indentation return line, false } // check for leading tabs (doesn't matter how many) if strings.HasPrefix(updatedLine, "\t") { // line is considered a code line by indentation return line, false } return updatedLine, true } // foreachLine iterates over the provided string and calls "process" method for each line. // If process returns false, or the scan reaches the end of the lines, the scanning stops. // The method returns the remaining text of s. func foreachLine(s string, process func(line string) bool) string { for len(s) > 0 { line, remaining, _ := strings.Cut(s, "\n") // always update s to the remaining string s = remaining // handle CLRF if lineLen := len(line); lineLen > 0 && line[lineLen-1] == '\r' { line = line[:lineLen-1] } if !process(line) { return s } } return s } // cutLongestPrefix returns the longest prefix of repeating 'c' together with the remainder of the string. func cutLongestPrefix(s string, c rune) (string, string) { if len(s) == 0 { return "", "" } i := strings.IndexFunc(s, func(r rune) bool { return r != c }) if i < 0 { // no character found that's different from the provided rune! return s, "" } return s[:i], s[i:] }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/pr_state.go
app/api/controller/pullreq/pr_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 pullreq import ( "context" "fmt" "strconv" "time" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" gitenum "github.com/harness/gitness/git/enum" "github.com/harness/gitness/git/sha" gitness_store "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/gotidy/ptr" "github.com/rs/zerolog/log" ) type StateInput struct { State enum.PullReqState `json:"state"` IsDraft bool `json:"is_draft"` } func (in *StateInput) Check() error { state, ok := in.State.Sanitize() // Sanitize will pass through also merged state, so we must check later for it. if !ok { return usererror.BadRequest(fmt.Sprintf("Allowed states are: %s and %s", enum.PullReqStateOpen, enum.PullReqStateClosed)) } in.State = state if in.State == enum.PullReqStateMerged { return usererror.BadRequest("Pull requests can't be merged with this API") } return nil } // State updates the pull request's current state. // //nolint:gocognit,funlen func (c *Controller) State(ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, in *StateInput, ) (*types.PullReq, error) { if err := in.Check(); err != nil { return nil, err } targetRepo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to target repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, targetRepo.ID, pullreqNum) if err != nil { return nil, fmt.Errorf("failed to get pull request by number: %w", err) } if pr.State == enum.PullReqStateMerged { return nil, usererror.BadRequest("Merged pull requests can't be modified.") } if pr.State == in.State && in.IsDraft == pr.IsDraft { return pr, nil // no changes are necessary: state is the same and is_draft hasn't change } id := pr.ID var sourceRepo *types.RepositoryCore switch { case pr.SourceRepoID == nil: // the source repo is purged sourceRepo = nil case *pr.SourceRepoID != pr.TargetRepoID: // if the source repo is nil, it's soft deleted sourceRepo, err = c.repoFinder.FindByID(ctx, *pr.SourceRepoID) if err != nil && !errors.Is(err, gitness_store.ErrResourceNotFound) { return nil, fmt.Errorf("failed to get source repo by id: %w", err) } if sourceRepo != nil { if err = apiauth.CheckRepo(ctx, c.authorizer, session, sourceRepo, enum.PermissionRepoPush); err != nil { return nil, fmt.Errorf("failed to acquire access to target repo: %w", err) } } default: sourceRepo = targetRepo if err = apiauth.CheckRepo(ctx, c.authorizer, session, targetRepo, enum.PermissionRepoPush); err != nil { return nil, fmt.Errorf("failed to acquire access to source repo: %w", err) } } targetWriteParams, err := controller.CreateRPCSystemReferencesWriteParams(ctx, c.urlProvider, session, targetRepo) if err != nil { return nil, fmt.Errorf("failed to create RPC write params: %w", err) } oldState := pr.State oldDraft := pr.IsDraft type change int const ( changeReopen change = iota + 1 changeClose ) var sourceSHA sha.SHA var mergeBaseSHA sha.SHA var targetSHA sha.SHA var stateChange change //nolint:nestif // refactor if needed if pr.State != enum.PullReqStateOpen && in.State == enum.PullReqStateOpen { if sourceRepo == nil { return nil, usererror.BadRequest("Forked repository doesn't exist anymore.") } if sourceSHA, err = c.verifyBranchExistence(ctx, sourceRepo, pr.SourceBranch); err != nil { return nil, err } if _, err = c.verifyBranchExistence(ctx, targetRepo, pr.TargetBranch); err != nil { return nil, err } err = c.checkIfAlreadyExists(ctx, pr.TargetRepoID, *pr.SourceRepoID, pr.TargetBranch, pr.SourceBranch) if err != nil { return nil, err } if targetRepo.ID != sourceRepo.ID { _, err = c.git.FetchObjects(ctx, &git.FetchObjectsParams{ WriteParams: targetWriteParams, Source: sourceRepo.GitUID, ObjectSHAs: []sha.SHA{sourceSHA}, }) if err != nil { return nil, fmt.Errorf("failed to fetch git objects from the source repository: %w", err) } } targetReadParams := git.CreateReadParams(targetRepo) targetRef, err := c.git.GetRef(ctx, git.GetRefParams{ ReadParams: targetReadParams, Name: pr.TargetBranch, Type: gitenum.RefTypeBranch, }) if err != nil { return nil, fmt.Errorf("failed to resolve target branch reference: %w", err) } targetSHA = targetRef.SHA mergeBaseResult, err := c.git.MergeBase(ctx, git.MergeBaseParams{ ReadParams: targetReadParams, Ref1: sourceSHA.String(), Ref2: targetSHA.String(), }) if err != nil { return nil, fmt.Errorf("failed to find merge base: %w", err) } mergeBaseSHA = mergeBaseResult.MergeBaseSHA if mergeBaseSHA == sourceSHA { return nil, usererror.BadRequest("The source branch doesn't contain any new commits") } stateChange = changeReopen } else if pr.State == enum.PullReqStateOpen && in.State != enum.PullReqStateOpen { stateChange = changeClose } err = controller.TxOptLock(ctx, c.tx, func(ctx context.Context) error { if pr == nil { pr, err = c.pullreqStore.Find(ctx, id) if err != nil { return fmt.Errorf("failed to find pull request by id: %w", err) } } pr.State = in.State pr.IsDraft = in.IsDraft switch stateChange { case changeClose: nowMilli := time.Now().UnixMilli() // clear all merge (check) related fields pr.MergeSHA = nil pr.Closed = &nowMilli pr.MarkAsMergeUnchecked() // delete the merge pull request reference err = c.git.UpdateRef(ctx, git.UpdateRefParams{ WriteParams: targetWriteParams, Name: strconv.FormatInt(pr.Number, 10), Type: gitenum.RefTypePullReqMerge, NewValue: sha.Nil, OldValue: sha.None, // we don't care about the old value }) case changeReopen: pr.SourceSHA = sourceSHA.String() pr.MergeTargetSHA = ptr.String(targetSHA.String()) pr.MergeBaseSHA = mergeBaseSHA.String() pr.Closed = nil // create the head pull request reference err = c.git.UpdateRef(ctx, git.UpdateRefParams{ WriteParams: targetWriteParams, Name: strconv.FormatInt(pr.Number, 10), Type: gitenum.RefTypePullReqHead, NewValue: sourceSHA, OldValue: sha.None, // the request is re-opened, so anything can be the old value }) if err != nil { return fmt.Errorf("failed to set value of PR head ref: %w", err) } } pr.ActivitySeq++ // because we need to add the activity entry err = c.pullreqStore.Update(ctx, pr) if err != nil { return fmt.Errorf("failed to update pull request: %w", err) } return nil }, controller.TxOptionResetFunc(func() { pr = nil // on the version conflict error force re-fetch of the pull request })) if err != nil { return nil, fmt.Errorf("failed to update pull request: %w", err) } payload := &types.PullRequestActivityPayloadStateChange{ Old: oldState, New: pr.State, OldDraft: oldDraft, NewDraft: pr.IsDraft, } if _, errAct := c.activityStore.CreateWithPayload(ctx, pr, session.Principal.ID, payload, nil); errAct != nil { // non-critical error log.Ctx(ctx).Err(errAct).Msgf("failed to write pull request activity after state change") } switch stateChange { case changeReopen: c.eventReporter.Reopened(ctx, &pullreqevents.ReopenedPayload{ Base: eventBase(pr, &session.Principal), SourceBranch: pr.SourceBranch, SourceSHA: sourceSHA.String(), MergeBaseSHA: mergeBaseSHA.String(), }) case changeClose: c.eventReporter.Closed(ctx, &pullreqevents.ClosedPayload{ Base: eventBase(pr, &session.Principal), SourceSHA: pr.SourceSHA, SourceBranch: pr.SourceBranch, }) } c.sseStreamer.Publish(ctx, targetRepo.ParentID, enum.SSETypePullReqUpdated, pr) return pr, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/activity_list_test.go
app/api/controller/pullreq/activity_list_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 pullreq import ( "testing" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "golang.org/x/exp/slices" ) func TestRemoveDeletedComments(t *testing.T) { type activity struct { id int64 kind enum.PullReqActivityKind order int64 subOrder int64 deleted *int64 } var n int64 d := &n tests := []struct { name string input []activity want []int64 }{ { name: "nothing-deleted", input: []activity{ {id: 1, kind: enum.PullReqActivityKindComment, order: 0, subOrder: 0, deleted: nil}, {id: 2, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 0, deleted: nil}, {id: 3, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 1, deleted: nil}, {id: 4, kind: enum.PullReqActivityKindComment, order: 2, subOrder: 0, deleted: nil}, {id: 5, kind: enum.PullReqActivityKindComment, order: 2, subOrder: 1, deleted: nil}, }, want: []int64{1, 2, 3, 4, 5}, }, { name: "deleted-thread", input: []activity{ {id: 1, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 0, deleted: d}, {id: 2, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 1, deleted: d}, {id: 3, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 2, deleted: d}, }, want: []int64{}, }, { name: "deleted-top-level-replies-not", input: []activity{ {id: 1, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 0, deleted: d}, {id: 2, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 1, deleted: nil}, {id: 3, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 2, deleted: d}, }, want: []int64{1, 2, 3}, }, { name: "deleted-all-replies", input: []activity{ {id: 1, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 0, deleted: nil}, {id: 2, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 1, deleted: d}, {id: 3, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 2, deleted: d}, }, want: []int64{1, 2, 3}, }, { name: "complex", input: []activity{ // kind=system, deleted, must not be removed {id: 1, kind: enum.PullReqActivityKindSystem, order: 0, subOrder: 0, deleted: d}, // thread size=1, not deleted {id: 2, kind: enum.PullReqActivityKindComment, order: 1, subOrder: 0, deleted: nil}, // thread size=1, deleted {id: 3, kind: enum.PullReqActivityKindComment, order: 2, subOrder: 0, deleted: d}, // kind=system, not deleted, must not be removed {id: 4, kind: enum.PullReqActivityKindSystem, order: 3, subOrder: 0, deleted: nil}, // thread size=2, not deleted {id: 5, kind: enum.PullReqActivityKindComment, order: 4, subOrder: 0, deleted: nil}, {id: 6, kind: enum.PullReqActivityKindComment, order: 4, subOrder: 1, deleted: d}, // thread size=2, change comment, deleted {id: 7, kind: enum.PullReqActivityKindChangeComment, order: 5, subOrder: 0, deleted: d}, {id: 8, kind: enum.PullReqActivityKindChangeComment, order: 5, subOrder: 1, deleted: d}, }, want: []int64{1, 2, 4, 5, 6}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { list := make([]*types.PullReqActivity, len(test.input)) for i := range test.input { list[i] = &types.PullReqActivity{ ID: test.input[i].id, Kind: test.input[i].kind, Order: test.input[i].order, SubOrder: test.input[i].subOrder, Deleted: test.input[i].deleted, } } var got []int64 for _, act := range removeDeletedComments(list) { got = append(got, act.ID) } if !slices.Equal(test.want, got) { t.Errorf("want=%v got=%v", test.want, got) } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/branch_delete.go
app/api/controller/pullreq/branch_delete.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/audit" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // DeleteBranch deletes the source branch of a PR. func (c *Controller) DeleteBranch(ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, bypassRules, dryRunRules bool, ) (types.DeleteBranchOutput, []types.RuleViolations, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return types.DeleteBranchOutput{}, nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return types.DeleteBranchOutput{}, nil, fmt.Errorf("failed to get pull request by number: %w", err) } branchName := pr.SourceBranch // make sure user isn't deleting the default branch if branchName == repo.DefaultBranch { return types.DeleteBranchOutput{}, nil, usererror.ErrDefaultBranchCantBeDeleted } rules, isRepoOwner, err := c.fetchRules(ctx, session, repo) if err != nil { return types.DeleteBranchOutput{}, nil, fmt.Errorf("failed to fetch rules: %w", err) } violations, err := rules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: bypassRules, IsRepoOwner: isRepoOwner, Repo: repo, RefAction: protection.RefActionDelete, RefType: protection.RefTypeBranch, RefNames: []string{branchName}, }) if err != nil { return types.DeleteBranchOutput{}, nil, fmt.Errorf("failed to verify protection rules: %w", err) } if dryRunRules { return types.DeleteBranchOutput{ DryRunRulesOutput: types.DryRunRulesOutput{ DryRunRules: true, RuleViolations: violations, }, }, nil, nil } if protection.IsCritical(violations) { return types.DeleteBranchOutput{}, violations, nil } writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return types.DeleteBranchOutput{}, nil, fmt.Errorf("failed to create RPC write params: %w", err) } branch, err := func() (types.Branch, error) { rpcOut, err := c.git.GetBranch(ctx, &git.GetBranchParams{ ReadParams: git.CreateReadParams(repo), BranchName: branchName, }) if err != nil { return types.Branch{}, fmt.Errorf("failed to fetch source branch: %w", err) } mappedBranch, err := controller.MapBranch(rpcOut.Branch) if err != nil { return types.Branch{}, fmt.Errorf("failed to map source branch: %w", err) } return mappedBranch, nil }() if err != nil { return types.DeleteBranchOutput{}, nil, err } if pr.SourceSHA != branch.SHA.String() { return types.DeleteBranchOutput{}, nil, errors.Conflict("source branch SHA does not match pull request source SHA") } err = c.git.DeleteBranch(ctx, &git.DeleteBranchParams{ WriteParams: writeParams, BranchName: branchName, SHA: branch.SHA.String(), }) if err != nil { return types.DeleteBranchOutput{}, nil, err } err = func() error { if pr, err = c.pullreqStore.UpdateActivitySeq(ctx, pr); err != nil { return fmt.Errorf("failed to update pull request activity sequence: %w", err) } _, err := c.activityStore.CreateWithPayload(ctx, pr, session.Principal.ID, &types.PullRequestActivityPayloadBranchDelete{SHA: branch.SHA.String()}, nil) return err }() if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to write pull request activity for successful branch delete") } if protection.IsBypassed(violations) { err = c.auditService.Log(ctx, session.Principal, audit.NewResource( audit.ResourceTypeRepository, repo.Identifier, audit.RepoPath, repo.Path, audit.BypassedResourceType, audit.BypassedResourceTypeBranch, audit.BypassedResourceName, branchName, audit.BypassAction, audit.BypassActionDeleted, audit.ResourceName, fmt.Sprintf( audit.BypassSHALabelFormat, repo.Identifier, branchName, ), ), audit.ActionBypassed, paths.Parent(repo.Path), audit.WithNewObject(audit.BranchObject{ BranchName: branchName, RepoPath: repo.Path, RuleViolations: violations, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for delete branch operation: %s", err) } } return types.DeleteBranchOutput{ DryRunRulesOutput: types.DryRunRulesOutput{ RuleViolations: violations, }}, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/codeowner.go
app/api/controller/pullreq/codeowner.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/codeowners" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c *Controller) CodeOwners( ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, ) (types.CodeOwnerEvaluation, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return types.CodeOwnerEvaluation{}, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return types.CodeOwnerEvaluation{}, fmt.Errorf("failed to get pull request by number: %w", err) } reviewers, err := c.reviewerStore.List(ctx, pr.ID) if err != nil { return types.CodeOwnerEvaluation{}, fmt.Errorf("failed to get reviewers by pr: %w", err) } ownerEvaluation, err := c.codeOwners.Evaluate(ctx, repo, pr, reviewers) if err != nil { return types.CodeOwnerEvaluation{}, err } return types.CodeOwnerEvaluation{ EvaluationEntries: mapCodeOwnerEvaluation(ownerEvaluation), FileSha: ownerEvaluation.FileSha, }, nil } func mapCodeOwnerEvaluation(ownerEvaluation *codeowners.Evaluation) []types.CodeOwnerEvaluationEntry { codeOwnerEvaluationEntries := make([]types.CodeOwnerEvaluationEntry, len(ownerEvaluation.EvaluationEntries)) for i, entry := range ownerEvaluation.EvaluationEntries { ownerEvaluations := make([]types.OwnerEvaluation, len(entry.UserEvaluations)) userGroupOwnerEvaluations := make([]types.UserGroupOwnerEvaluation, len(entry.UserGroupEvaluations)) for j, owner := range entry.UserEvaluations { ownerEvaluations[j] = mapOwner(owner) } for j, userGroupOwnerEvaluation := range entry.UserGroupEvaluations { userGroupEvaluations := make([]types.OwnerEvaluation, len(userGroupOwnerEvaluation.Evaluations)) for k, userGroupOwner := range userGroupOwnerEvaluation.Evaluations { userGroupEvaluations[k] = mapOwner(userGroupOwner) } userGroupOwnerEvaluations[j] = types.UserGroupOwnerEvaluation{ ID: userGroupOwnerEvaluation.Identifier, Name: userGroupOwnerEvaluation.Name, Evaluations: userGroupEvaluations, } } codeOwnerEvaluationEntries[i] = types.CodeOwnerEvaluationEntry{ LineNumber: entry.LineNumber, Pattern: entry.Pattern, OwnerEvaluations: ownerEvaluations, UserGroupOwnerEvaluations: userGroupOwnerEvaluations, } } return codeOwnerEvaluationEntries } func mapOwner(owner codeowners.UserEvaluation) types.OwnerEvaluation { return types.OwnerEvaluation{ Owner: owner.Owner, ReviewDecision: owner.ReviewDecision, ReviewSHA: owner.ReviewSHA, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/reviewer_delete.go
app/api/controller/pullreq/reviewer_delete.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 pullreq import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // ReviewerDelete deletes reviewer from the reviewer list for the given PR. func (c *Controller) ReviewerDelete( ctx context.Context, session *auth.Session, repoRef string, prNum int64, reviewerID int64, ) error { repo, err := c.getRepo(ctx, repoRef) if err != nil { return fmt.Errorf("failed to find repository: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return fmt.Errorf("failed to find pull request: %w", err) } reviewer, err := c.reviewerStore.Find(ctx, pr.ID, reviewerID) if err != nil { return fmt.Errorf("failed to find reviewer: %w", err) } var reqPermission enum.Permission switch { case session.Principal.ID == reviewer.PrincipalID: reqPermission = enum.PermissionRepoReview // Anybody can remove their own reviews with RepoReview permission. case reviewer.ReviewDecision == enum.PullReqReviewDecisionPending: reqPermission = enum.PermissionRepoPush // The reviewer was asked for a review but didn't submit it yet. default: reqPermission = enum.PermissionRepoEdit // RepoEdit permission is required to remove a submitted review. } // Make sure the repository state allows delete reviewer operation. if err = apiauth.CheckRepoState(ctx, session, repo, reqPermission); err != nil { return err } // Make sure the caller has the right permission even if the PR is merged, so that we can return the correct error. if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, reqPermission); err != nil { return fmt.Errorf("access check failed: %w", err) } if pr.Merged != nil { return usererror.BadRequest("Pull request is already merged") } err = c.reviewerStore.Delete(ctx, pr.ID, reviewerID) if err != nil { return fmt.Errorf("failed to delete reviewer: %w", err) } err = func() error { payload := &types.PullRequestActivityPayloadReviewerDelete{ CommitSHA: reviewer.SHA, Decision: reviewer.ReviewDecision, PrincipalID: reviewer.PrincipalID, } metadata := &types.PullReqActivityMetadata{ Mentions: &types.PullReqActivityMentionsMetadata{IDs: []int64{reviewer.PrincipalID}}, } if pr, err = c.pullreqStore.UpdateActivitySeq(ctx, pr); err != nil { return fmt.Errorf("failed to increment pull request activity sequence: %w", err) } _, err = c.activityStore.CreateWithPayload(ctx, pr, session.Principal.ID, payload, metadata) if err != nil { return fmt.Errorf("failed to create pull request activity: %w", err) } return nil }() if err != nil { // non-critical error log.Ctx(ctx).Err(err).Msg("failed to write pull request activity after reviewer removal") } c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypePullReqReviewerAdded, pr) return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/pr_commits.go
app/api/controller/pullreq/pr_commits.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // Commits lists all commits from pr head branch. func (c *Controller) Commits( ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, filter *types.PaginationFilter, ) ([]types.Commit, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return nil, fmt.Errorf("failed to get pull request by number: %w", err) } gitRef := pr.SourceSHA afterRef := pr.MergeBaseSHA output, err := c.git.ListCommits(ctx, &git.ListCommitsParams{ ReadParams: git.CreateReadParams(repo), GitREF: gitRef, After: afterRef, Page: int32(filter.Page), //nolint:gosec Limit: int32(filter.Limit), //nolint:gosec }) if err != nil { return nil, err } commits := make([]types.Commit, len(output.Commits)) for i := range output.Commits { commits[i] = *controller.MapCommit(&output.Commits[i]) } return commits, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/review_submit.go
app/api/controller/pullreq/review_submit.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 pullreq import ( "context" "errors" "fmt" "time" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" events "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/git" "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type ReviewSubmitInput struct { CommitSHA string `json:"commit_sha"` Decision enum.PullReqReviewDecision `json:"decision"` } func (in *ReviewSubmitInput) Validate() error { if in.CommitSHA == "" { return usererror.BadRequest("CommitSHA is a mandatory field") } decision, ok := in.Decision.Sanitize() if !ok || decision == enum.PullReqReviewDecisionPending { msg := fmt.Sprintf("Decision must be: %q, %q or %q.", enum.PullReqReviewDecisionApproved, enum.PullReqReviewDecisionChangeReq, enum.PullReqReviewDecisionReviewed) return usererror.BadRequest(msg) } in.Decision = decision return nil } // ReviewSubmit creates a new pull request review. func (c *Controller) ReviewSubmit( ctx context.Context, session *auth.Session, repoRef string, prNum int64, in *ReviewSubmitInput, ) (*types.PullReqReview, error) { if err := in.Validate(); err != nil { return nil, err } repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return nil, fmt.Errorf("failed to find pull request by number: %w", err) } if pr.Merged != nil { return nil, usererror.BadRequest("Can't submit a review for merged pull requests") } if pr.CreatedBy == session.Principal.ID { return nil, usererror.BadRequest("Can't submit review to own pull requests.") } commit, err := c.git.GetCommit(ctx, &git.GetCommitParams{ ReadParams: git.ReadParams{RepoUID: repo.GitUID}, Revision: in.CommitSHA, }) if err != nil { return nil, fmt.Errorf("failed to get git branch sha: %w", err) } commitSHA := commit.Commit.SHA var review *types.PullReqReview err = c.tx.WithTx(ctx, func(ctx context.Context) error { now := time.Now().UnixMilli() review = &types.PullReqReview{ ID: 0, CreatedBy: session.Principal.ID, Created: now, Updated: now, PullReqID: pr.ID, Decision: in.Decision, SHA: commitSHA.String(), } err = c.reviewStore.Create(ctx, review) if err != nil { return err } c.eventReporter.ReviewSubmitted(ctx, &events.ReviewSubmittedPayload{ Base: eventBase(pr, &session.Principal), Decision: review.Decision, ReviewerID: review.CreatedBy, }) _, err = c.updateReviewer(ctx, session, pr, review, commitSHA.String()) return err }) if err != nil { return nil, err } err = func() error { if pr, err = c.pullreqStore.UpdateActivitySeq(ctx, pr); err != nil { return fmt.Errorf("failed to increment pull request activity sequence: %w", err) } payload := &types.PullRequestActivityPayloadReviewSubmit{ CommitSHA: commitSHA.String(), Decision: in.Decision, } _, err = c.activityStore.CreateWithPayload(ctx, pr, session.Principal.ID, payload, nil) return err }() if err != nil { // non-critical error log.Ctx(ctx).Err(err).Msgf("failed to write pull request activity after review submit") } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeReviewPullRequest, Principal: session.Principal.ToPrincipalInfo(), Path: repo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, instrument.PropertyPullRequestID: pr.Number, instrument.PropertyDecision: in.Decision, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for review pull request operation: %s", err) } return review, nil } // updateReviewer updates pull request reviewer object. func (c *Controller) updateReviewer( ctx context.Context, session *auth.Session, pr *types.PullReq, review *types.PullReqReview, sha string, ) (*types.PullReqReviewer, error) { reviewer, err := c.reviewerStore.Find(ctx, pr.ID, session.Principal.ID) if err != nil && !errors.Is(err, store.ErrResourceNotFound) { return nil, err } if reviewer != nil { reviewer.LatestReviewID = &review.ID reviewer.ReviewDecision = review.Decision reviewer.SHA = sha err = c.reviewerStore.Update(ctx, reviewer) } else { now := time.Now().UnixMilli() reviewer = &types.PullReqReviewer{ PullReqID: pr.ID, PrincipalID: session.Principal.ID, CreatedBy: session.Principal.ID, Created: now, Updated: now, RepoID: pr.TargetRepoID, Type: enum.PullReqReviewerTypeSelfAssigned, LatestReviewID: &review.ID, ReviewDecision: review.Decision, SHA: sha, Reviewer: types.PrincipalInfo{}, AddedBy: types.PrincipalInfo{}, } err = c.reviewerStore.Create(ctx, reviewer) c.reportReviewerAddition(ctx, session, pr, reviewer) } if err != nil { return nil, fmt.Errorf("failed to create/update reviewer") } return reviewer, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/pr_create.go
app/api/controller/pullreq/pr_create.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 pullreq import ( "context" "fmt" "strconv" "strings" "time" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/services/codeowners" "github.com/harness/gitness/app/services/instrument" labelsvc "github.com/harness/gitness/app/services/label" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/app/services/usergroup" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" gitenum "github.com/harness/gitness/git/enum" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/gotidy/ptr" "github.com/rs/zerolog/log" "golang.org/x/exp/maps" ) type CreateInput struct { IsDraft bool `json:"is_draft"` Title string `json:"title"` Description string `json:"description"` SourceRepoRef string `json:"source_repo_ref"` SourceBranch string `json:"source_branch"` TargetBranch string `json:"target_branch"` ReviewerIDs []int64 `json:"reviewer_ids"` UserGroupReviewerIDs []int64 `json:"user_group_reviewer_ids"` Labels []*types.PullReqLabelAssignInput `json:"labels"` BypassRules bool `json:"bypass_rules"` } func (in *CreateInput) Sanitize() error { in.Title = strings.TrimSpace(in.Title) in.Description = strings.TrimSpace(in.Description) if err := validateTitle(in.Title); err != nil { return err } if err := validateDescription(in.Description); err != nil { return err } return nil } // Create creates a new pull request. func (c *Controller) Create( ctx context.Context, session *auth.Session, repoRef string, in *CreateInput, ) (*types.PullReq, error) { if err := in.Sanitize(); err != nil { return nil, err } permissionRequired := enum.PermissionRepoPush if in.SourceRepoRef != "" { permissionRequired = enum.PermissionRepoView } targetRepo, err := c.getRepoCheckAccess(ctx, session, repoRef, permissionRequired) if err != nil { return nil, fmt.Errorf("failed to acquire access to target repo: %w", err) } sourceRepo := targetRepo if in.SourceRepoRef != "" { sourceRepo, err = c.getRepoCheckAccess(ctx, session, in.SourceRepoRef, enum.PermissionRepoPush) if err != nil { return nil, fmt.Errorf("failed to acquire access to source repo: %w", err) } } if sourceRepo.ID == targetRepo.ID && in.TargetBranch == in.SourceBranch { return nil, usererror.BadRequest("Target and source branch can't be the same") } var sourceSHA sha.SHA if sourceSHA, err = c.verifyBranchExistence(ctx, sourceRepo, in.SourceBranch); err != nil { return nil, err } if _, err = c.verifyBranchExistence(ctx, targetRepo, in.TargetBranch); err != nil { return nil, err } if err = c.checkIfAlreadyExists(ctx, targetRepo.ID, sourceRepo.ID, in.TargetBranch, in.SourceBranch); err != nil { return nil, err } targetWriteParams, err := controller.CreateRPCSystemReferencesWriteParams( ctx, c.urlProvider, session, targetRepo, ) if err != nil { return nil, fmt.Errorf("failed to create RPC write params: %w", err) } if targetRepo.ID != sourceRepo.ID { _, err = c.git.FetchObjects(ctx, &git.FetchObjectsParams{ WriteParams: targetWriteParams, Source: sourceRepo.GitUID, ObjectSHAs: []sha.SHA{sourceSHA}, }) if err != nil { return nil, fmt.Errorf("failed to fetch git objects from the source repository: %w", err) } } targetReadParams := git.CreateReadParams(targetRepo) targetRef, err := c.git.GetRef(ctx, git.GetRefParams{ ReadParams: targetReadParams, Name: in.TargetBranch, Type: gitenum.RefTypeBranch, }) if err != nil { return nil, fmt.Errorf("failed to resolve target branch reference: %w", err) } targetSHA := targetRef.SHA mergeBaseResult, err := c.git.MergeBase(ctx, git.MergeBaseParams{ ReadParams: targetReadParams, Ref1: sourceSHA.String(), Ref2: targetSHA.String(), }) if err != nil { return nil, fmt.Errorf("failed to find merge base: %w", err) } mergeBaseSHA := mergeBaseResult.MergeBaseSHA if mergeBaseSHA == sourceSHA { return nil, usererror.BadRequest("The source branch doesn't contain any new commits") } prStats, err := c.git.DiffStats(ctx, &git.DiffParams{ ReadParams: targetReadParams, BaseRef: mergeBaseSHA.String(), HeadRef: sourceSHA.String(), }) if err != nil { return nil, fmt.Errorf("failed to fetch PR diff stats: %w", err) } var pr *types.PullReq var activitySeq int64 // Payload based reviewers userReviewerMap, userGroupReviewerMap, err := c.prepareRequestedReviewers( ctx, session, in.ReviewerIDs, in.UserGroupReviewerIDs, targetRepo, ) if err != nil { return nil, fmt.Errorf("failed to prepare requested reviewers: %w", err) } // save user and user group IDs for activity creation later requestedUserReviewerIDs := maps.Keys(userReviewerMap) requestedUserGroupReviewerIDs := maps.Keys(userGroupReviewerMap) if len(userReviewerMap) > 0 { activitySeq++ } if len(userGroupReviewerMap) > 0 { activitySeq++ } // Rules based reviewers out, err := c.createPullReqVerify(ctx, session, targetRepo, in) if err != nil { return nil, fmt.Errorf("failed to get create pull request protection: %w", err) } ownerUserReviewerMap, ownerUserGroupReviewerMap, err := c.getCodeOwnerReviewers( ctx, out.RequestCodeOwners, session.Principal.ID, targetRepo, in.TargetBranch, mergeBaseSHA.String(), sourceSHA.String(), ) if err != nil { // error on codeowners can happen due to multiple reasons like file not exist or incorrect file format // logging the error is good enough log.Ctx(ctx).Warn().Err(err).Msg("failed to prepare code owner reviewers") } if len(ownerUserReviewerMap) > 0 { activitySeq++ } if len(ownerUserGroupReviewerMap) > 0 { activitySeq++ } defaultUserReviewerMap, defaultUserGroupReviewerMap, err := c.getDefaultReviewers( ctx, session.Principal.ID, out.DefaultReviewerIDs, out.DefaultGroupReviewerIDs, ) if err != nil { return nil, fmt.Errorf("failed to prepare default reviewers: %w", err) } if len(defaultUserReviewerMap) > 0 { activitySeq++ } if len(defaultUserGroupReviewerMap) > 0 { activitySeq++ } for _, reviewer := range ownerUserReviewerMap { if _, ok := userReviewerMap[reviewer.ID]; !ok { userReviewerMap[reviewer.ID] = reviewer } } for _, reviewer := range defaultUserReviewerMap { if _, ok := userReviewerMap[reviewer.ID]; !ok { userReviewerMap[reviewer.ID] = reviewer } } for identifier, userGroup := range ownerUserGroupReviewerMap { if _, ok := userGroupReviewerMap[identifier]; !ok { userGroupReviewerMap[identifier] = userGroup } } for _, reviewer := range defaultUserGroupReviewerMap { if _, ok := userGroupReviewerMap[reviewer.ID]; !ok { userGroupReviewerMap[reviewer.ID] = reviewer } } // Prepare label assign input var labelAssignOuts []*labelsvc.AssignToPullReqOut labelAssignInputMap, err := c.prepareLabels( ctx, in.Labels, session.Principal.ID, targetRepo.ID, targetRepo.ParentID, ) if err != nil { return nil, fmt.Errorf("failed to prepare labels: %w", err) } if len(labelAssignInputMap) > 0 { activitySeq++ } err = controller.TxOptLock(ctx, c.tx, func(ctx context.Context) error { // Always re-fetch at the start of the transaction because the repo we have is from a cache. targetRepoFull, err := c.repoStore.Find(ctx, targetRepo.ID) if err != nil { return fmt.Errorf("failed to find repository: %w", err) } // Update the repository's pull request sequence number targetRepoFull.PullReqSeq++ err = c.repoStore.Update(ctx, targetRepoFull) if err != nil { return fmt.Errorf("failed to update pullreq sequence number: %w", err) } // Create pull request in the DB number := targetRepoFull.PullReqSeq now := time.Now().UnixMilli() pr = &types.PullReq{ ID: 0, // the ID will be populated in the data layer Version: 0, Number: number, CreatedBy: session.Principal.ID, Created: now, Updated: now, Edited: now, State: enum.PullReqStateOpen, IsDraft: in.IsDraft, Title: in.Title, Description: in.Description, SourceRepoID: &sourceRepo.ID, SourceBranch: in.SourceBranch, SourceSHA: sourceSHA.String(), TargetRepoID: targetRepo.ID, TargetBranch: in.TargetBranch, ActivitySeq: 0, MergedBy: nil, Merged: nil, MergeMethod: nil, MergeTargetSHA: ptr.String(targetSHA.String()), MergeBaseSHA: mergeBaseSHA.String(), MergeCheckStatus: enum.MergeCheckStatusUnchecked, RebaseCheckStatus: enum.MergeCheckStatusUnchecked, Author: *session.Principal.ToPrincipalInfo(), Merger: nil, Stats: types.PullReqStats{ DiffStats: types.NewDiffStats(prStats.Commits, prStats.FilesChanged, prStats.Additions, prStats.Deletions), Conversations: 0, UnresolvedCount: 0, }, } targetRepo = targetRepoFull.Core() pr.ActivitySeq = activitySeq err = c.pullreqStore.Create(ctx, pr) if err != nil { return fmt.Errorf("pullreq creation failed: %w", err) } // reset pr activity seq: we increment pr.ActivitySeq on activity creation pr.ActivitySeq = 0 // Create reviewers and assign labels if err = c.createUserReviewers(ctx, session, userReviewerMap, targetRepo, pr); err != nil { return fmt.Errorf("failed to create user reviewers: %w", err) } if err = c.createUserGroupReviewers(ctx, session, userGroupReviewerMap, targetRepo, pr); err != nil { return fmt.Errorf("failed to create user group reviewers: %w", err) } if labelAssignOuts, err = c.assignLabels(ctx, pr, session.Principal.ID, labelAssignInputMap); err != nil { return fmt.Errorf("failed to assign labels: %w", err) } // Create PR head reference in the git repository err = c.git.UpdateRef(ctx, git.UpdateRefParams{ WriteParams: targetWriteParams, Name: strconv.FormatInt(targetRepoFull.PullReqSeq, 10), Type: gitenum.RefTypePullReqHead, NewValue: sourceSHA, OldValue: sha.None, // we don't care about the old value }) if err != nil { return fmt.Errorf("failed to create PR head ref: %w", err) } return nil }) if err != nil { return nil, fmt.Errorf("failed to create pullreq: %w", err) } c.storeCreateReviewerActivity( ctx, pr, session.Principal.ID, requestedUserReviewerIDs, enum.PullReqReviewerTypeRequested, ) c.storeCreateUserGroupReviewerActivity( ctx, pr, session.Principal.ID, requestedUserGroupReviewerIDs, enum.PullReqReviewerTypeRequested, ) c.storeCreateReviewerActivity( ctx, pr, session.Principal.ID, maps.Keys(ownerUserReviewerMap), enum.PullReqReviewerTypeCodeOwners, ) c.storeCreateUserGroupReviewerActivity( ctx, pr, session.Principal.ID, maps.Keys(ownerUserGroupReviewerMap), enum.PullReqReviewerTypeCodeOwners, ) c.storeCreateReviewerActivity( ctx, pr, session.Principal.ID, maps.Keys(defaultUserReviewerMap), enum.PullReqReviewerTypeDefault, ) c.storeCreateUserGroupReviewerActivity( ctx, pr, session.Principal.ID, maps.Keys(defaultUserGroupReviewerMap), enum.PullReqReviewerTypeDefault, ) backfillWithLabelAssignInfo(pr, labelAssignOuts) c.storeLabelAssignActivity(ctx, pr, session.Principal.ID, labelAssignOuts) c.eventReporter.Created(ctx, &pullreqevents.CreatedPayload{ Base: eventBase(pr, &session.Principal), SourceBranch: in.SourceBranch, TargetBranch: in.TargetBranch, SourceSHA: sourceSHA.String(), ReviewerIDs: maps.Keys(userReviewerMap), }) c.sseStreamer.Publish(ctx, targetRepo.ParentID, enum.SSETypePullReqUpdated, pr) err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeCreatePullRequest, Principal: session.Principal.ToPrincipalInfo(), Path: sourceRepo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: sourceRepo.ID, instrument.PropertyRepositoryName: sourceRepo.Identifier, instrument.PropertyPullRequestID: pr.Number, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for create pull request operation: %s", err) } return pr, nil } // prepareRequestedReviewers fetches principal data and checks principal repo access and permissions. // The data recency is not critical: principals might change and the op will either be valid or fail. // Because it makes db calls, we use it before, i.e. outside of the PR creation tx. func (c *Controller) prepareRequestedReviewers( ctx context.Context, session *auth.Session, reviewers []int64, userGroupReviewers []int64, repo *types.RepositoryCore, ) (map[int64]*types.PrincipalInfo, map[int64]*types.UserGroup, error) { // Process individual user reviewers principalMap := make(map[int64]*types.PrincipalInfo, len(reviewers)) for _, id := range reviewers { if id == session.Principal.ID { return nil, nil, usererror.BadRequest("PR creator cannot be added as a reviewer.") } reviewerPrincipal, err := c.principalStore.Find(ctx, id) if err != nil { return nil, nil, usererror.BadRequest("Failed to find principal reviewer.") } // TODO: To check the reviewer's access to the repo we create a dummy session object. Fix it. if err = apiauth.CheckRepo( ctx, c.authorizer, &auth.Session{ Principal: *reviewerPrincipal, Metadata: nil, }, repo, enum.PermissionRepoReview, ); err != nil { if !errors.Is(err, apiauth.ErrForbidden) { return nil, nil, usererror.BadRequest( "The reviewer doesn't have enough permissions for the repository.", ) } return nil, nil, fmt.Errorf("reviewer principal %s check repo access error: %w", reviewerPrincipal.UID, err) } principalMap[reviewerPrincipal.ID] = reviewerPrincipal.ToPrincipalInfo() } // Process user group reviewers userGroupMap := make(map[int64]*types.UserGroup, len(userGroupReviewers)) var err error if len(userGroupReviewers) > 0 { // skip trip to db if no user group reviewers userGroupMap, err = c.userGroupStore.FindManyByIDs(ctx, userGroupReviewers) if err != nil { return nil, nil, fmt.Errorf("failed to find many user groups by IDs: %w", err) } } return principalMap, userGroupMap, nil } func (c *Controller) createPullReqVerify( ctx context.Context, session *auth.Session, targetRepo *types.RepositoryCore, in *CreateInput, ) (*protection.CreatePullReqVerifyOutput, error) { rules, isRepoOwner, err := c.fetchRules(ctx, session, targetRepo) if err != nil { return nil, fmt.Errorf("failed to fetch protection rules: %w", err) } out, _, err := rules.CreatePullReqVerify(ctx, protection.CreatePullReqVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: in.BypassRules, IsRepoOwner: isRepoOwner, DefaultBranch: targetRepo.DefaultBranch, TargetBranch: in.TargetBranch, RepoID: targetRepo.ID, RepoIdentifier: targetRepo.Identifier, }) if err != nil { return nil, fmt.Errorf("failed to verify protection rules: %w", err) } return &out, nil } func (c *Controller) getCodeOwnerReviewers( ctx context.Context, requestCodeOwners bool, sessionPrincipalID int64, targetRepo *types.RepositoryCore, targetBranch string, mergeBaseSHA string, sourceSHA string, ) (map[int64]*types.PrincipalInfo, map[int64]*types.UserGroup, error) { if !requestCodeOwners { return map[int64]*types.PrincipalInfo{}, map[int64]*types.UserGroup{}, nil } applicableOwners, err := c.codeOwners.GetApplicableCodeOwners( ctx, targetRepo, targetBranch, mergeBaseSHA, sourceSHA, ) if errors.Is(err, codeowners.ErrNotFound) { return map[int64]*types.PrincipalInfo{}, map[int64]*types.UserGroup{}, nil } if err != nil { return nil, nil, fmt.Errorf("failed to get applicable code owners: %w", err) } var userEmails []string var userGroupIdentifiers []string for _, entry := range applicableOwners.Entries { for _, owner := range entry.Owners { if identifier, ok := codeowners.ParseUserGroupOwner(owner); ok { userGroupIdentifiers = append(userGroupIdentifiers, identifier) } else { userEmails = append(userEmails, owner) } } } // Process individual user reviewers var userMap map[int64]*types.PrincipalInfo if len(userEmails) > 0 { users, err := c.principalStore.FindManyByEmail(ctx, userEmails) if err != nil { return nil, nil, fmt.Errorf("failed to find many principals by email: %w", err) } userMap = make(map[int64]*types.PrincipalInfo, len(users)) for _, users := range users { userMap[users.ID] = users.ToPrincipalInfo() } // ensure we remove author from list delete(userMap, sessionPrincipalID) } // Process user group reviewers var userGroupMap map[int64]*types.UserGroup if len(userGroupIdentifiers) > 0 { // skip resolution if no user group identifiers identifierUserGroupMap := make(map[string]*types.UserGroup, len(userGroupIdentifiers)) for _, identifier := range userGroupIdentifiers { // do not resolve user groups if already resolved if _, ok := identifierUserGroupMap[identifier]; ok { continue } userGroup, err := c.userGroupResolver.Resolve(ctx, identifier) if errors.Is(err, usergroup.ErrNotFound) { log.Ctx(ctx).Warn().Msgf("user group %q not found, skipping", identifier) continue } if err != nil { return nil, nil, fmt.Errorf("failed to resolve user group %q: %w", identifier, err) } identifierUserGroupMap[identifier] = userGroup } userGroupMap = make(map[int64]*types.UserGroup, len(identifierUserGroupMap)) for _, userGroup := range identifierUserGroupMap { userGroupMap[userGroup.ID] = userGroup } } return userMap, userGroupMap, nil } func (c *Controller) getDefaultReviewers( ctx context.Context, sessionPrincipalID int64, reviewerIDs []int64, defaultGroupReviewerIDs []int64, ) (map[int64]*types.PrincipalInfo, map[int64]*types.UserGroup, error) { var err error var principals map[int64]*types.PrincipalInfo if len(reviewerIDs) > 0 { // skip cache query if no reviewer IDs principals, err = c.principalInfoCache.Map(ctx, reviewerIDs) if err != nil { return nil, nil, fmt.Errorf("failed to find principal infos by ids: %w", err) } } var userGroupMap map[int64]*types.UserGroup if len(defaultGroupReviewerIDs) > 0 { // skip trip to user group store if no group reviewer IDs userGroupMap, err = c.userGroupStore.FindManyByIDs(ctx, defaultGroupReviewerIDs) if err != nil { return nil, nil, fmt.Errorf("failed to find user group reviewers by ids: %w", err) } } // ensure we remove author from list delete(principals, sessionPrincipalID) return principals, userGroupMap, nil } func (c *Controller) createUserReviewers( ctx context.Context, session *auth.Session, principalInfos map[int64]*types.PrincipalInfo, repo *types.RepositoryCore, pr *types.PullReq, ) error { if len(principalInfos) == 0 { return nil } requestedBy := session.Principal.ToPrincipalInfo() for _, principalInfo := range principalInfos { reviewer := newPullReqReviewer( session, pr, repo, principalInfo, requestedBy, enum.PullReqReviewerTypeRequested, &ReviewerAddInput{ReviewerID: principalInfo.ID}, ) if err := c.reviewerStore.Create(ctx, reviewer); err != nil { return fmt.Errorf("failed to create pull request reviewer: %w", err) } } return nil } func (c *Controller) createUserGroupReviewers( ctx context.Context, session *auth.Session, userGroups map[int64]*types.UserGroup, repo *types.RepositoryCore, pr *types.PullReq, ) error { if len(userGroups) == 0 { return nil } now := time.Now().UnixMilli() addedBy := session.Principal.ToPrincipalInfo() for _, userGroup := range userGroups { reviewer := &types.UserGroupReviewer{ PullReqID: pr.ID, UserGroupID: userGroup.ID, CreatedBy: addedBy.ID, Created: now, Updated: now, RepoID: repo.ID, UserGroup: *userGroup.ToUserGroupInfo(), AddedBy: *addedBy, Decision: enum.PullReqReviewDecisionPending, } if err := c.userGroupReviewerStore.Create(ctx, reviewer); err != nil { return fmt.Errorf("failed to create user group pull request reviewer: %w", err) } } return nil } func (c *Controller) storeCreateReviewerActivity( ctx context.Context, pr *types.PullReq, authorID int64, reviewerIDs []int64, reviewerType enum.PullReqReviewerType, ) { if len(reviewerIDs) == 0 { return } pr.ActivitySeq++ payload := &types.PullRequestActivityPayloadReviewerAdd{ ReviewerType: reviewerType, PrincipalIDs: reviewerIDs, } metadata := &types.PullReqActivityMetadata{ Mentions: &types.PullReqActivityMentionsMetadata{IDs: reviewerIDs}, } if _, err := c.activityStore.CreateWithPayload( ctx, pr, authorID, payload, metadata, ); err != nil { log.Ctx(ctx).Err(err).Msgf( "failed to write create %s reviewer pull req activity", reviewerType, ) } } func (c *Controller) storeCreateUserGroupReviewerActivity( ctx context.Context, pr *types.PullReq, authorID int64, userGroupIDs []int64, reviewerType enum.PullReqReviewerType, ) { if len(userGroupIDs) == 0 { return } pr.ActivitySeq++ payload := &types.PullRequestActivityPayloadUserGroupReviewerAdd{ UserGroupIDs: userGroupIDs, ReviewerType: reviewerType, } metadata := &types.PullReqActivityMetadata{ Mentions: &types.PullReqActivityMentionsMetadata{ UserGroupIDs: userGroupIDs, }, } if _, err := c.activityStore.CreateWithPayload( ctx, pr, authorID, payload, metadata, ); err != nil { log.Ctx(ctx).Err(err).Msgf( "failed to write create %s user group reviewer pull req activity", reviewerType, ) } } // prepareLabels fetches data (labels and label values) necessary for the pr label assignment. // The data recency is not critical: labels/values might change and the op will either be valid or fail. // Because it makes db calls, we use it before, i.e. outside of the PR creation tx. func (c *Controller) prepareLabels( ctx context.Context, labelAssignInputs []*types.PullReqLabelAssignInput, principalID int64, repoID int64, repoParentID int64, ) (map[*types.PullReqLabelAssignInput]*labelsvc.WithValue, error) { labelAssignInputMap := make( map[*types.PullReqLabelAssignInput]*labelsvc.WithValue, len(labelAssignInputs), ) for _, labelAssignInput := range labelAssignInputs { labelWithValue, err := c.labelSvc.PreparePullReqLabel( ctx, principalID, repoID, repoParentID, labelAssignInput, ) if err != nil { return nil, fmt.Errorf("failed to prepare label assignment data: %w", err) } labelAssignInputMap[labelAssignInput] = &labelWithValue } return labelAssignInputMap, nil } // assignLabels is a critical op for PR creation, so we use it in the PR creation tx. func (c *Controller) assignLabels( ctx context.Context, pr *types.PullReq, principalID int64, labelAssignInputMap map[*types.PullReqLabelAssignInput]*labelsvc.WithValue, ) ([]*labelsvc.AssignToPullReqOut, error) { assignOuts := make([]*labelsvc.AssignToPullReqOut, len(labelAssignInputMap)) var err error var i int for labelAssignInput, labelWithValue := range labelAssignInputMap { assignOuts[i], err = c.labelSvc.AssignToPullReqOnCreation( ctx, pr.ID, principalID, labelWithValue, labelAssignInput, ) if err != nil { return nil, fmt.Errorf("failed to assign label to pullreq: %w", err) } i++ } return assignOuts, nil } func backfillWithLabelAssignInfo( pr *types.PullReq, labelAssignOuts []*labelsvc.AssignToPullReqOut, ) { pr.Labels = make([]*types.LabelPullReqAssignmentInfo, len(labelAssignOuts)) for i, assignOut := range labelAssignOuts { pr.Labels[i] = assignOut.ToLabelPullReqAssignmentInfo() } } func (c *Controller) storeLabelAssignActivity( ctx context.Context, pr *types.PullReq, principalID int64, labelAssignOuts []*labelsvc.AssignToPullReqOut, ) { if len(labelAssignOuts) == 0 { return } pr.ActivitySeq++ payload := &types.PullRequestActivityLabels{ Labels: make([]*types.PullRequestActivityLabelBase, len(labelAssignOuts)), Type: enum.LabelActivityAssign, } for i, out := range labelAssignOuts { var value *string var valueColor *enum.LabelColor if out.NewLabelValue != nil { value = &out.NewLabelValue.Value valueColor = &out.NewLabelValue.Color } payload.Labels[i] = &types.PullRequestActivityLabelBase{ Label: out.Label.Key, LabelColor: out.Label.Color, LabelScope: out.Label.Scope, Value: value, ValueColor: valueColor, } } if _, err := c.activityStore.CreateWithPayload( ctx, pr, principalID, payload, nil, ); err != nil { log.Ctx(ctx).Err(err).Msg("failed to write label assign pull req activity") } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/branch_restore.go
app/api/controller/pullreq/branch_restore.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/audit" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // RestoreBranchInput used for branch restoration apis. type RestoreBranchInput struct { DryRunRules bool `json:"dry_run_rules"` BypassRules bool `json:"bypass_rules"` } // RestoreBranch restores branch for the merged/closed PR. func (c *Controller) RestoreBranch(ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, in *RestoreBranchInput, ) (types.CreateBranchOutput, []types.RuleViolations, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return types.CreateBranchOutput{}, nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return types.CreateBranchOutput{}, nil, fmt.Errorf("failed to get pull request by number: %w", err) } if pr.State == enum.PullReqStateOpen { return types.CreateBranchOutput{}, nil, errors.Conflictf("source branch %q already exists", pr.SourceBranch) } rules, isRepoOwner, err := c.fetchRules(ctx, session, repo) if err != nil { return types.CreateBranchOutput{}, nil, fmt.Errorf("failed to fetch rules: %w", err) } violations, err := rules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: in.BypassRules, IsRepoOwner: isRepoOwner, Repo: repo, RefAction: protection.RefActionCreate, RefType: protection.RefTypeBranch, RefNames: []string{pr.SourceBranch}, }) if err != nil { return types.CreateBranchOutput{}, nil, fmt.Errorf("failed to verify protection rules: %w", err) } if in.DryRunRules { return types.CreateBranchOutput{ DryRunRulesOutput: types.DryRunRulesOutput{ DryRunRules: true, RuleViolations: violations, }, }, nil, nil } if protection.IsCritical(violations) { return types.CreateBranchOutput{}, violations, nil } writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return types.CreateBranchOutput{}, nil, fmt.Errorf("failed to create RPC write params: %w", err) } rpcOut, err := c.git.CreateBranch(ctx, &git.CreateBranchParams{ WriteParams: writeParams, BranchName: pr.SourceBranch, Target: pr.SourceSHA, }) if err != nil { return types.CreateBranchOutput{}, nil, err } branch, err := controller.MapBranch(rpcOut.Branch) if err != nil { return types.CreateBranchOutput{}, nil, fmt.Errorf("failed to map branch: %w", err) } if protection.IsBypassed(violations) { err = c.auditService.Log(ctx, session.Principal, audit.NewResource( audit.ResourceTypeRepository, repo.Identifier, audit.RepoPath, repo.Path, audit.BypassedResourceType, audit.BypassedResourceTypeBranch, audit.BypassedResourceName, branch.Name, audit.BypassAction, audit.BypassActionCreated, audit.ResourceName, fmt.Sprintf( audit.BypassSHALabelFormat, repo.Identifier, branch.Name, ), ), audit.ActionBypassed, paths.Parent(repo.Path), audit.WithNewObject(audit.BranchObject{ BranchName: branch.Name, RepoPath: repo.Path, RuleViolations: violations, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for restore branch operation: %s", err) } } err = func() error { if pr, err = c.pullreqStore.UpdateActivitySeq(ctx, pr); err != nil { return fmt.Errorf("failed to update pull request activity sequence: %w", err) } _, err := c.activityStore.CreateWithPayload(ctx, pr, session.Principal.ID, &types.PullRequestActivityPayloadBranchRestore{SHA: pr.SourceSHA}, nil) return err }() if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to write pull request activity for successful branch restore") } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeCreateBranch, Principal: session.Principal.ToPrincipalInfo(), Path: repo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for create branch operation: %s", err) } return types.CreateBranchOutput{ Branch: branch, DryRunRulesOutput: types.DryRunRulesOutput{ RuleViolations: violations, }, }, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/label_list.go
app/api/controller/pullreq/label_list.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListLabels list labels assigned to a specified pullreq. func (c *Controller) ListLabels( ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, filter *types.AssignableLabelFilter, ) (*types.ScopesLabels, int64, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to target repo: %w", err) } pullreq, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return nil, 0, fmt.Errorf("failed to find pullreq: %w", err) } scopeLabelsMap, total, err := c.labelSvc.ListPullReqLabels( ctx, repo, repo.ParentID, pullreq.ID, filter) if err != nil { return nil, 0, fmt.Errorf("failed to list pullreq labels: %w", err) } return scopeLabelsMap, total, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/pr_update.go
app/api/controller/pullreq/pr_update.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 pullreq import ( "context" "fmt" "strings" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/errors" gitness_store "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type UpdateInput struct { Title string `json:"title"` Description string `json:"description"` } func (in *UpdateInput) Sanitize() error { in.Title = strings.TrimSpace(in.Title) in.Description = strings.TrimSpace(in.Description) if err := validateTitle(in.Title); err != nil { return err } if err := validateDescription(in.Description); err != nil { return err } return nil } // Update updates an pull request. func (c *Controller) Update(ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, in *UpdateInput, ) (*types.PullReq, error) { if err := in.Sanitize(); err != nil { return nil, err } targetRepo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to target repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, targetRepo.ID, pullreqNum) if err != nil { return nil, fmt.Errorf("failed to get pull request by number: %w", err) } switch { case pr.SourceRepoID == nil: // the source repo is purged case *pr.SourceRepoID != pr.TargetRepoID: // if the source repo is nil, it's soft deleted sourceRepo, err := c.repoFinder.FindByID(ctx, *pr.SourceRepoID) if err != nil && !errors.Is(err, gitness_store.ErrResourceNotFound) { return nil, fmt.Errorf("failed to get source repo by id: %w", err) } if sourceRepo != nil { if err = apiauth.CheckRepo(ctx, c.authorizer, session, sourceRepo, enum.PermissionRepoPush); err != nil { return nil, fmt.Errorf("failed to acquire access to source repo: %w", err) } } default: if err = apiauth.CheckRepo(ctx, c.authorizer, session, targetRepo, enum.PermissionRepoPush); err != nil { return nil, fmt.Errorf("failed to acquire access to target repo: %w", err) } } titleOld := pr.Title descriptionOld := pr.Description titleChanged := titleOld != in.Title descriptionChanged := descriptionOld != in.Description if !titleChanged && !descriptionChanged { return pr, nil } needToWriteActivity := titleChanged pr, err = c.pullreqStore.UpdateOptLock(ctx, pr, func(pr *types.PullReq) error { pr.Title = in.Title pr.Description = in.Description if needToWriteActivity { pr.ActivitySeq++ } return nil }) if err != nil { return pr, fmt.Errorf("failed to update pull request: %w", err) } if needToWriteActivity { payload := &types.PullRequestActivityPayloadTitleChange{ Old: titleOld, New: pr.Title, } if _, errAct := c.activityStore.CreateWithPayload(ctx, pr, session.Principal.ID, payload, nil); errAct != nil { // non-critical error log.Ctx(ctx).Err(errAct).Msgf("failed to write pull request activity after title change") } } updateEvent := &pullreqevents.UpdatedPayload{ Base: eventBase(pr, &session.Principal), } if titleChanged { updateEvent.TitleChanged = titleChanged updateEvent.TitleOld = titleOld updateEvent.TitleNew = pr.Title } if descriptionChanged { updateEvent.DescriptionChanged = descriptionChanged updateEvent.DescriptionOld = descriptionOld updateEvent.DescriptionNew = pr.Description } c.eventReporter.Updated(ctx, updateEvent) c.sseStreamer.Publish(ctx, targetRepo.ParentID, enum.SSETypePullReqUpdated, pr) return pr, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/comment_apply_suggestions.go
app/api/controller/pullreq/comment_apply_suggestions.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 pullreq import ( "context" "fmt" "strings" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/contextutil" "github.com/harness/gitness/git" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/gotidy/ptr" "github.com/rs/zerolog/log" ) type SuggestionReference struct { CommentID int64 `json:"comment_id"` CheckSum string `json:"check_sum"` } func (e *SuggestionReference) sanitize() error { if e.CommentID <= 0 { return usererror.BadRequest("Comment ID has to be a positive number.") } e.CheckSum = strings.TrimSpace(e.CheckSum) if e.CheckSum == "" { return usererror.BadRequest("Check sum has to be provided.") } return nil } type CommentApplySuggestionsInput struct { Suggestions []SuggestionReference `json:"suggestions"` Title string `json:"title"` Message string `json:"message"` DryRunRules bool `json:"dry_run_rules"` BypassRules bool `json:"bypass_rules"` } func (i *CommentApplySuggestionsInput) sanitize() error { if len(i.Suggestions) == 0 { return usererror.BadRequest("No suggestions provided.") } for _, suggestion := range i.Suggestions { if err := suggestion.sanitize(); err != nil { return err } } // cleanup title / message (NOTE: git doesn't support white space only) i.Title = strings.TrimSpace(i.Title) i.Message = strings.TrimSpace(i.Message) return nil } type CommentApplySuggestionsOutput struct { CommitID string `json:"commit_id"` types.DryRunRulesOutput } // CommentApplySuggestions applies suggestions for code comments. // //nolint:gocognit,gocyclo,cyclop func (c *Controller) CommentApplySuggestions( ctx context.Context, session *auth.Session, repoRef string, prNum int64, in *CommentApplySuggestionsInput, ) (CommentApplySuggestionsOutput, []types.RuleViolations, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf("failed to find pull request by number: %w", err) } if err := in.sanitize(); err != nil { return CommentApplySuggestionsOutput{}, nil, err } // verify branch rules protectionRules, isRepoOwner, err := c.fetchRules(ctx, session, repo) if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf("failed to fetch rules: %w", err) } violations, err := protectionRules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: in.BypassRules, IsRepoOwner: isRepoOwner, Repo: repo, RefAction: protection.RefActionUpdate, RefType: protection.RefTypeBranch, RefNames: []string{pr.SourceBranch}, }) if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf("failed to verify protection rules: %w", err) } if in.DryRunRules { return CommentApplySuggestionsOutput{ DryRunRulesOutput: types.DryRunRulesOutput{ DryRunRules: true, RuleViolations: violations, }, }, nil, nil } if protection.IsCritical(violations) { return CommentApplySuggestionsOutput{}, violations, nil } actions := []git.CommitFileAction{} type activityUpdate struct { act *types.PullReqActivity resolve bool checksum string } activityUpdates := map[int64]activityUpdate{} // cache file shas to reduce number of git calls (use commit as some code comments can be temp out of sync) getFileSHAKey := func(commitID string, path string) string { return commitID + ":" + path } fileSHACache := map[string]sha.SHA{} for _, suggestionEntry := range in.Suggestions { activity, err := c.getCommentForPR(ctx, pr, suggestionEntry.CommentID) if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf( "failed to find activity %d: %w", suggestionEntry.CommentID, err) } var ccActivity *types.PullReqActivity if activity.IsValidCodeComment() { ccActivity = activity } else if activity.ParentID != nil { parentActivity, err := c.activityStore.Find(ctx, *activity.ParentID) if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf( "failed to find parent activity %d: %w", *activity.ParentID, err) } if parentActivity.IsValidCodeComment() { ccActivity = parentActivity } } if ccActivity == nil { return CommentApplySuggestionsOutput{}, nil, usererror.BadRequest( "Only code comments or replies on code comments support applying suggestions.") } // code comment can't be part of multiple suggestions being applied if _, ok := activityUpdates[ccActivity.ID]; ok { return CommentApplySuggestionsOutput{}, nil, usererror.BadRequestf( "Code comment %d is part of multiple suggestions being applied.", ccActivity.ID, ) } // retrieve and verify code comment data cc := ccActivity.AsCodeComment() if cc.Outdated { return CommentApplySuggestionsOutput{}, nil, usererror.BadRequest( "Suggestions by outdated code comments cannot be applied.") } // retrieve and verify code comment payload payload, err := ccActivity.GetPayload() if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf( "failed to get payload of related code comment activity %d: %w", ccActivity.ID, err) } ccPayload, ok := payload.(*types.PullRequestActivityPayloadCodeComment) if !ok { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf( "provided code comment activity %d has payload of wrong type %T", ccActivity.ID, payload) } if !ccPayload.LineStartNew || !ccPayload.LineEndNew { return CommentApplySuggestionsOutput{}, nil, usererror.BadRequest( "Only suggestions on the PR source branch can be applied.") } suggestions := parseSuggestions(activity.Text) var suggestionToApply *suggestion for i := range suggestions { if strings.EqualFold(suggestions[i].checkSum, suggestionEntry.CheckSum) { suggestionToApply = &suggestions[i] break } } if suggestionToApply == nil { return CommentApplySuggestionsOutput{}, nil, usererror.NotFoundf( "No suggestion found for activity %d that matches check sum %q.", suggestionEntry.CommentID, suggestionEntry.CheckSum, ) } // use file-sha for optimistic locking on file to avoid any racing conditions. fileSHAKey := getFileSHAKey(cc.SourceSHA, cc.Path) fileSHA, ok := fileSHACache[fileSHAKey] if !ok { node, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{ ReadParams: git.CreateReadParams(repo), GitREF: cc.SourceSHA, Path: cc.Path, IncludeLatestCommit: false, }) if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf( "failed to read tree node for commit %q path %q: %w", cc.SourceSHA, cc.Path, err, ) } // TODO: git api should return sha.SHA type fileSHA = sha.Must(node.Node.SHA) fileSHACache[fileSHAKey] = fileSHA } // add suggestion to actions actions = append(actions, git.CommitFileAction{ Action: git.PatchTextAction, Path: cc.Path, SHA: fileSHA, Payload: fmt.Appendf(nil, "%d:%d\u0000%s", cc.LineNew, cc.LineNew+cc.SpanNew, suggestionToApply.code, ), }) activityUpdates[activity.ID] = activityUpdate{ act: activity, checksum: suggestionToApply.checkSum, resolve: ccActivity == activity, } if ccActivity != activity { activityUpdates[ccActivity.ID] = activityUpdate{ act: ccActivity, resolve: true, } } } // we want to complete the operation independent of request cancel - start with new, time restricted context. // TODO: This is a small change to reduce likelihood of dirty state (e.g. git work done but db canceled). // We still require a proper solution to handle an application crash or very slow execution times const timeout = 1 * time.Minute ctx, cancel := contextutil.WithNewTimeout(ctx, timeout) defer cancel() // Create internal write params. Note: This will skip the pre-commit protection rules check. writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf("failed to create RPC write params: %w", err) } // backfill title if not provided (keeping it basic for now, user can provide more detailed title) if in.Title == "" { in.Title = "Apply code review suggestions" } now := time.Now() commitOut, err := c.git.CommitFiles(ctx, &git.CommitFilesParams{ WriteParams: writeParams, Message: git.CommitMessage(in.Title, in.Message), Branch: pr.SourceBranch, Committer: controller.SystemServicePrincipalInfo(), CommitterDate: &now, Author: controller.IdentityFromPrincipalInfo(*session.Principal.ToPrincipalInfo()), AuthorDate: &now, Actions: actions, }) if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf("failed to commit changes: %w", err) } // update activities (use UpdateOptLock as it can have racing condition with comment migration) resolved := ptr.Of(now.UnixMilli()) resolvedBy := &session.Principal.ID resolvedActivities := map[int64]struct{}{} for _, update := range activityUpdates { _, err = c.activityStore.UpdateOptLock(ctx, update.act, func(act *types.PullReqActivity) error { // only resolve where required (can happen in case of parallel resolution of activity) if update.resolve && act.Resolved == nil { act.Resolved = resolved act.ResolvedBy = resolvedBy resolvedActivities[act.ID] = struct{}{} } else { delete(resolvedActivities, act.ID) } if update.checksum != "" { act.UpdateMetadata(types.WithPullReqActivitySuggestionsMetadataUpdate( func(s *types.PullReqActivitySuggestionsMetadata) { s.AppliedCheckSum = update.checksum s.AppliedCommitSHA = commitOut.CommitID.String() })) } return nil }) if err != nil { // best effort - commit already happened log.Ctx(ctx).Warn().Err(err).Msgf("failed to update activity %d after applying suggestions", update.act.ID) } } // This is a best effort approach as in case of sqlite a transaction is likely to be blocked // by parallel event-triggered db writes from the above commit. // WARNING: This could cause the count to diverge (similar to create / delete). // TODO: Use transaction once sqlite issue has been addressed. pr, err = c.pullreqStore.UpdateOptLock(ctx, pr, func(pr *types.PullReq) error { pr.UnresolvedCount -= len(resolvedActivities) return nil }) if err != nil { return CommentApplySuggestionsOutput{}, nil, fmt.Errorf("failed to update pull request's unresolved comment count: %w", err) } c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypePullReqUpdated, pr) err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypePRSuggestionApplied, Principal: session.Principal.ToPrincipalInfo(), Path: repo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, instrument.PropertyPullRequestID: pr.Number, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf( "failed to insert instrumentation record for pull request suggestion applied operation: %s", err, ) } return CommentApplySuggestionsOutput{ CommitID: commitOut.CommitID.String(), DryRunRulesOutput: types.DryRunRulesOutput{ RuleViolations: violations, }, }, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/pr_find.go
app/api/controller/pullreq/pr_find.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // Find returns a pull request from the provided repository. func (c *Controller) Find( ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, options types.PullReqMetadataOptions, ) (*types.PullReq, error) { if pullreqNum <= 0 { return nil, usererror.BadRequest("A valid pull request number must be provided.") } repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to the repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return nil, err } err = c.labelSvc.Backfill(ctx, pr) if err != nil { return nil, fmt.Errorf("failed to backfill labels assigned to pull request: %w", err) } if err := c.pullreqListService.BackfillMetadataForPullReq(ctx, repo, pr, options); err != nil { return nil, fmt.Errorf("failed to backfill pull request metadata: %w", err) } return pr, nil } // FindByBranches returns a pull request from the provided branch pair. func (c *Controller) FindByBranches( ctx context.Context, session *auth.Session, repoRef, sourceRepoRef, sourceBranch, targetBranch string, options types.PullReqMetadataOptions, ) (*types.PullReq, error) { if sourceBranch == "" || targetBranch == "" { return nil, usererror.BadRequest("A valid source/target branch must be provided.") } targetRepo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to the repo: %w", err) } sourceRepo := targetRepo if sourceRepoRef != repoRef { sourceRepo, err = c.getRepoCheckAccess(ctx, session, sourceRepoRef, enum.PermissionRepoPush) if err != nil { return nil, fmt.Errorf("failed to acquire access to source repo: %w", err) } } prs, err := c.pullreqStore.List(ctx, &types.PullReqFilter{ SourceRepoID: sourceRepo.ID, SourceBranch: sourceBranch, TargetRepoID: targetRepo.ID, TargetBranch: targetBranch, States: []enum.PullReqState{enum.PullReqStateOpen}, Size: 1, Sort: enum.PullReqSortNumber, Order: enum.OrderAsc, }) if err != nil { return nil, fmt.Errorf("failed to fetch existing pull request: %w", err) } if len(prs) == 0 { return nil, usererror.ErrNotFound } if err := c.pullreqListService.BackfillMetadataForPullReq(ctx, targetRepo, prs[0], options); err != nil { return nil, fmt.Errorf("failed to backfill pull request metadata: %w", err) } return prs[0], nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/usergroup_reviewer_delete.go
app/api/controller/pullreq/usergroup_reviewer_delete.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // UserGroupReviewerDelete deletes reviewer from the UserGroupReviewers store for the given PR. func (c *Controller) UserGroupReviewerDelete( ctx context.Context, session *auth.Session, repoRef string, prNum, userGroupID int64, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return fmt.Errorf("failed to find pull request: %w", err) } err = c.userGroupReviewerStore.Delete(ctx, pr.ID, userGroupID) if err != nil { return fmt.Errorf("failed to delete user group reviewer: %w", err) } err = func() error { if pr, err = c.pullreqStore.UpdateActivitySeq(ctx, pr); err != nil { return fmt.Errorf("failed to increment pull request activity sequence: %w", err) } payload := &types.PullRequestActivityPayloadUserGroupReviewerDelete{ UserGroupIDs: []int64{userGroupID}, } metadata := &types.PullReqActivityMetadata{ Mentions: &types.PullReqActivityMentionsMetadata{UserGroupIDs: []int64{userGroupID}}, } _, err = c.activityStore.CreateWithPayload(ctx, pr, session.Principal.ID, payload, metadata) if err != nil { return fmt.Errorf("failed to create pull request activity: %w", err) } return nil }() if err != nil { log.Ctx(ctx).Err(err).Msg("failed to write pull request activity after user group reviewer removal") } return err }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/comment_update.go
app/api/controller/pullreq/comment_update.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 pullreq import ( "context" "fmt" "strings" "time" "github.com/harness/gitness/app/auth" events "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type CommentUpdateInput struct { Text string `json:"text"` } func (in *CommentUpdateInput) Sanitize() error { in.Text = strings.TrimSpace(in.Text) if err := validateComment(in.Text); err != nil { return err } return nil } func (in *CommentUpdateInput) hasChanges(act *types.PullReqActivity) bool { return in.Text != act.Text } // CommentUpdate updates a pull request comment. func (c *Controller) CommentUpdate( ctx context.Context, session *auth.Session, repoRef string, prNum int64, commentID int64, in *CommentUpdateInput, ) (*types.PullReqActivity, error) { if err := in.Sanitize(); err != nil { return nil, err } repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return nil, fmt.Errorf("failed to find pull request by number: %w", err) } act, err := c.getCommentCheckEditAccess(ctx, session, pr, commentID) if err != nil { return nil, fmt.Errorf("failed to get comment: %w", err) } if !in.hasChanges(act) { return act, nil } // fetch parent activity var parentAct *types.PullReqActivity if act.IsReply() { parentAct, err = c.activityStore.Find(ctx, *act.ParentID) if err != nil { return nil, fmt.Errorf("failed to find parent pull request activity: %w", err) } } // generate all metadata updates var metadataUpdates []types.PullReqActivityMetadataUpdate metadataUpdates, principalInfos, err := c.appendMetadataUpdateForMentions( ctx, metadataUpdates, in.Text, ) if err != nil { return nil, fmt.Errorf("failed to update metadata for mentions: %w", err) } // suggestion metadata in case of code comments or code comment replies (don't restrict to either side for now). if act.IsValidCodeComment() || (act.IsReply() && parentAct.IsValidCodeComment()) { metadataUpdates = appendMetadataUpdateForSuggestions(metadataUpdates, in.Text) } act, err = c.activityStore.UpdateOptLock(ctx, act, func(act *types.PullReqActivity) error { now := time.Now().UnixMilli() act.Edited = now act.Text = in.Text act.UpdateMetadata(metadataUpdates...) return nil }) if err != nil { return nil, fmt.Errorf("failed to update comment: %w", err) } // Populate activity mentions (used only for response purposes). act.Mentions = principalInfos c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypePullReqUpdated, pr) c.reportCommentUpdated(ctx, pr, session.Principal.ID, act.ID, act.IsReply()) return act, nil } func (c *Controller) reportCommentUpdated( ctx context.Context, pr *types.PullReq, principalID int64, actID int64, isReply bool, ) { c.eventReporter.CommentUpdated(ctx, &events.CommentUpdatedPayload{ Base: events.Base{ PullReqID: pr.ID, SourceRepoID: pr.SourceRepoID, TargetRepoID: pr.TargetRepoID, PrincipalID: principalID, Number: pr.Number, }, ActivityID: actID, IsReply: isReply, }) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/controller.go
app/api/controller/pullreq/controller.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 pullreq import ( "context" "fmt" "unicode/utf8" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth/authz" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/services/codecomments" "github.com/harness/gitness/app/services/codeowners" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/label" locker "github.com/harness/gitness/app/services/locker" "github.com/harness/gitness/app/services/migrate" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/app/services/pullreq" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/services/usergroup" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/audit" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" gitenum "github.com/harness/gitness/git/enum" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type Controller struct { tx dbtx.Transactor urlProvider url.Provider authorizer authz.Authorizer auditService audit.Service pullreqStore store.PullReqStore activityStore store.PullReqActivityStore codeCommentView store.CodeCommentView reviewStore store.PullReqReviewStore reviewerStore store.PullReqReviewerStore userGroupReviewerStore store.UserGroupReviewerStore repoStore store.RepoStore principalStore store.PrincipalStore userGroupStore store.UserGroupStore principalInfoCache store.PrincipalInfoCache fileViewStore store.PullReqFileViewStore membershipStore store.MembershipStore checkStore store.CheckStore git git.Interface repoFinder refcache.RepoFinder eventReporter *pullreqevents.Reporter codeCommentMigrator *codecomments.Migrator pullreqService *pullreq.Service pullreqListService *pullreq.ListService protectionManager *protection.Manager sseStreamer sse.Streamer codeOwners *codeowners.Service locker *locker.Locker importer *migrate.PullReq labelSvc *label.Service instrumentation instrument.Service userGroupService usergroup.Service branchStore store.BranchStore userGroupResolver usergroup.Resolver } func NewController( tx dbtx.Transactor, urlProvider url.Provider, authorizer authz.Authorizer, auditService audit.Service, pullreqStore store.PullReqStore, pullreqActivityStore store.PullReqActivityStore, codeCommentView store.CodeCommentView, pullreqReviewStore store.PullReqReviewStore, pullreqReviewerStore store.PullReqReviewerStore, repoStore store.RepoStore, principalStore store.PrincipalStore, userGroupStore store.UserGroupStore, userGroupReviewerStore store.UserGroupReviewerStore, principalInfoCache store.PrincipalInfoCache, fileViewStore store.PullReqFileViewStore, membershipStore store.MembershipStore, checkStore store.CheckStore, git git.Interface, repoFinder refcache.RepoFinder, eventReporter *pullreqevents.Reporter, codeCommentMigrator *codecomments.Migrator, pullreqService *pullreq.Service, pullreqListService *pullreq.ListService, protectionManager *protection.Manager, sseStreamer sse.Streamer, codeowners *codeowners.Service, locker *locker.Locker, importer *migrate.PullReq, labelSvc *label.Service, instrumentation instrument.Service, userGroupService usergroup.Service, branchStore store.BranchStore, userGroupResolver usergroup.Resolver, ) *Controller { return &Controller{ tx: tx, urlProvider: urlProvider, authorizer: authorizer, auditService: auditService, pullreqStore: pullreqStore, activityStore: pullreqActivityStore, codeCommentView: codeCommentView, reviewStore: pullreqReviewStore, reviewerStore: pullreqReviewerStore, repoStore: repoStore, principalStore: principalStore, userGroupStore: userGroupStore, userGroupReviewerStore: userGroupReviewerStore, principalInfoCache: principalInfoCache, fileViewStore: fileViewStore, membershipStore: membershipStore, checkStore: checkStore, git: git, repoFinder: repoFinder, codeCommentMigrator: codeCommentMigrator, eventReporter: eventReporter, pullreqService: pullreqService, pullreqListService: pullreqListService, protectionManager: protectionManager, sseStreamer: sseStreamer, codeOwners: codeowners, locker: locker, importer: importer, labelSvc: labelSvc, instrumentation: instrumentation, userGroupService: userGroupService, branchStore: branchStore, userGroupResolver: userGroupResolver, } } func (c *Controller) verifyBranchExistence(ctx context.Context, repo *types.RepositoryCore, branch string, ) (sha.SHA, error) { if branch == "" { return sha.SHA{}, usererror.BadRequest("Branch name can't be empty") } ref, err := c.git.GetRef(ctx, git.GetRefParams{ ReadParams: git.ReadParams{RepoUID: repo.GitUID}, Name: branch, Type: gitenum.RefTypeBranch, }) if errors.AsStatus(err) == errors.StatusNotFound { return sha.SHA{}, usererror.BadRequest( fmt.Sprintf("branch %q does not exist in the repository %q", branch, repo.Identifier)) } if err != nil { return sha.SHA{}, fmt.Errorf( "failed to check existence of the branch %q in the repository %q: %w", branch, repo.Identifier, err) } return ref.SHA, nil } func (c *Controller) getRepo(ctx context.Context, repoRef string) (*types.RepositoryCore, error) { if repoRef == "" { return nil, usererror.BadRequest("A valid repository reference must be provided.") } repo, err := c.repoFinder.FindByRef(ctx, repoRef) if err != nil { return nil, fmt.Errorf("failed to find repository: %w", err) } return repo, nil } //nolint:unparam func (c *Controller) getRepoCheckAccess( ctx context.Context, session *auth.Session, repoRef string, reqPermission enum.Permission, allowedRepoStates ...enum.RepoState, ) (*types.RepositoryCore, error) { repo, err := c.getRepo(ctx, repoRef) if err != nil { return nil, err } if err := apiauth.CheckRepoState(ctx, session, repo, reqPermission, allowedRepoStates...); err != nil { return nil, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, reqPermission); err != nil { return nil, fmt.Errorf("access check failed: %w", err) } return repo, nil } func (c *Controller) fetchRules( ctx context.Context, session *auth.Session, repo *types.RepositoryCore, ) (protection.BranchProtection, bool, error) { isRepoOwner, err := apiauth.IsRepoOwner(ctx, c.authorizer, session, repo) if err != nil { return nil, false, fmt.Errorf("failed to determine if user is repo owner: %w", err) } protectionRules, err := c.protectionManager.ListRepoBranchRules(ctx, repo.ID) if err != nil { return nil, false, fmt.Errorf("failed to fetch protection rules for the repository: %w", err) } return protectionRules, isRepoOwner, nil } func (c *Controller) getCommentForPR( ctx context.Context, pr *types.PullReq, commentID int64, ) (*types.PullReqActivity, error) { if commentID <= 0 { return nil, usererror.BadRequest("A valid comment ID must be provided.") } comment, err := c.activityStore.Find(ctx, commentID) if err != nil { return nil, fmt.Errorf("failed to find comment by ID: %w", err) } if comment == nil { return nil, usererror.ErrNotFound } if comment.Deleted != nil || comment.RepoID != pr.TargetRepoID || comment.PullReqID != pr.ID { return nil, usererror.ErrNotFound } if comment.Kind == enum.PullReqActivityKindSystem { return nil, usererror.BadRequest("Can't update a comment created by the system.") } if comment.Type != enum.PullReqActivityTypeComment && comment.Type != enum.PullReqActivityTypeCodeComment { return nil, usererror.BadRequest("Only comments and code comments can be edited.") } return comment, nil } func (c *Controller) getCommentCheckEditAccess(ctx context.Context, session *auth.Session, pr *types.PullReq, commentID int64, ) (*types.PullReqActivity, error) { comment, err := c.getCommentForPR(ctx, pr, commentID) if err != nil { return nil, err } if comment.CreatedBy != session.Principal.ID { return nil, usererror.BadRequest("Only own comments may be updated.") } return comment, nil } func (c *Controller) getCommentCheckChangeStatusAccess(ctx context.Context, pr *types.PullReq, commentID int64, ) (*types.PullReqActivity, error) { comment, err := c.getCommentForPR(ctx, pr, commentID) if err != nil { return nil, err } if comment.SubOrder != 0 { return nil, usererror.BadRequest("Can't change status of replies.") } return comment, nil } func (c *Controller) checkIfAlreadyExists(ctx context.Context, targetRepoID, sourceRepoID int64, targetBranch, sourceBranch string, ) error { existing, err := c.pullreqStore.List(ctx, &types.PullReqFilter{ SourceRepoID: sourceRepoID, SourceBranch: sourceBranch, TargetRepoID: targetRepoID, TargetBranch: targetBranch, States: []enum.PullReqState{enum.PullReqStateOpen}, Size: 1, Sort: enum.PullReqSortNumber, Order: enum.OrderAsc, ExcludeDescription: true, }) if err != nil { return fmt.Errorf("failed to get existing pull requests: %w", err) } if len(existing) > 0 { return usererror.ConflictWithPayload( "A pull request for this target and source branch already exists", map[string]any{ "type": "pr already exists", "number": existing[0].Number, "title": existing[0].Title, }, ) } return nil } func eventBase(pr *types.PullReq, principal *types.Principal) pullreqevents.Base { return pullreqevents.Base{ PullReqID: pr.ID, SourceRepoID: pr.SourceRepoID, TargetRepoID: pr.TargetRepoID, Number: pr.Number, PrincipalID: principal.ID, } } func validateTitle(title string) error { if title == "" { return usererror.BadRequest("Pull request title can't be empty") } const maxLen = 256 if utf8.RuneCountInString(title) > maxLen { return usererror.BadRequestf("Pull request title is too long (maximum is %d characters)", maxLen) } return nil } func validateDescription(desc string) error { const maxLen = 64 << 10 // 64K if len(desc) > maxLen { return usererror.BadRequest("Pull request description is too long") } return nil } func validateComment(desc string) error { const maxLen = 16 << 10 // 16K if len(desc) > maxLen { return usererror.BadRequest("Pull request comment is too long") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/label_unassign.go
app/api/controller/pullreq/label_unassign.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // UnassignLabel removes a label from a pull request. func (c *Controller) UnassignLabel( ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, labelID int64, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return fmt.Errorf("failed to acquire access to target repo: %w", err) } pullreq, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return fmt.Errorf("failed to find pullreq: %w", err) } label, labelValue, err := c.labelSvc.UnassignFromPullReq( ctx, repo.ID, repo.ParentID, pullreq.ID, labelID) if err != nil { return fmt.Errorf("failed to delete pullreq label: %w", err) } pullreq, err = c.pullreqStore.UpdateActivitySeq(ctx, pullreq) if err != nil { return fmt.Errorf("failed to update pull request activity sequence: %w", err) } var value *string var color *enum.LabelColor if labelValue != nil { value = &labelValue.Value color = &labelValue.Color } payload := &types.PullRequestActivityLabel{ PullRequestActivityLabelBase: types.PullRequestActivityLabelBase{ Label: label.Key, LabelColor: label.Color, LabelScope: label.Scope, Value: value, ValueColor: color, }, Type: enum.LabelActivityUnassign, } if _, err := c.activityStore.CreateWithPayload( ctx, pullreq, session.Principal.ID, payload, nil); err != nil { log.Ctx(ctx).Err(err).Msg("failed to write pull request activity after label unassign") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/suggestions_test.go
app/api/controller/pullreq/suggestions_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 pullreq import ( "reflect" "testing" ) func Test_parseSuggestions(t *testing.T) { tests := []struct { name string arg string want []suggestion }{ { name: "test empty", arg: "", want: []suggestion{}, }, { name: "test no code block", arg: "a\nb", want: []suggestion{}, }, { name: "test indented code block", arg: " a\nb", want: []suggestion{}, }, { name: "test not enough fence markers (`)", arg: "`` suggestion\nb", want: []suggestion{}, }, { name: "test not enough fence markers (~)", arg: "~~ suggestion\nb", want: []suggestion{}, }, { name: "test indented fences start marker (` with space)", arg: " ``` suggestion\nb", want: []suggestion{}, }, { name: "test indented fence start marker (~ with tab)", arg: "\t~~~ suggestion\nb", want: []suggestion{}, }, { name: "test indented fence end marker (` with space)", arg: "``` suggestion\na\n ```\n", want: []suggestion{ { checkSum: "6e0f2a7504f8e96c862c0f963faea994e527bd32a1c5c2c79acbf6baf57854e7", code: "a\n ```", }, }, }, { name: "test indented fence end marker (~ with tab)", arg: "~~~ suggestion\na\n\t~~~\n", want: []suggestion{ { checkSum: "f5b959e235539ff7c9d2a687a1a5d05fa0c15e325dc50c83947c9d27c9d4fddf", code: "a\n\t~~~", }, }, }, { name: "test fence marker with invalid char (` with `)", arg: "``` suggestion `\nb", want: []suggestion{}, }, { name: "test wrong language (`)", arg: "``` abc\nb", want: []suggestion{}, }, { name: "test wrong language (~)", arg: "~~~ abc\nb", want: []suggestion{}, }, { name: "test language prefix (`)", arg: "``` suggestions\nb", want: []suggestion{}, }, { name: "test suggestion empty without code or endmarker (`)", arg: "``` suggestion", want: []suggestion{ { checkSum: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", code: "", }, }, }, { name: "test suggestion empty without endmarker (`)", arg: "``` suggestion\n", want: []suggestion{ { checkSum: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", code: "", }, }, }, { name: "test suggestion empty with endmarker (~)", arg: "~~~ suggestion\n~~~", want: []suggestion{ { checkSum: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", code: "", }, }, }, { name: "test suggestion newline only without endmarker (`)", arg: "``` suggestion\n\n", want: []suggestion{ { checkSum: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", code: "", // first \n is for end of header, second \n is for beginning of trailer }, }, }, { name: "test suggestion newline only without endmarker (`)", arg: "``` suggestion\n\n\n", want: []suggestion{ { checkSum: "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b", code: "\n", // first \n is for end of header, second \n is for beginning of trailer }, }, }, { name: "test suggestion without end and line without newline (`)", arg: "``` suggestion\na", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, }, }, { name: "test suggestion without end and line with newline (~)", arg: "~~~ suggestion\na\n", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, }, }, { name: "test suggestion with wrong end (`)", arg: "``` suggestion\na\n~~~", want: []suggestion{ { checkSum: "862bb949147c31270cce026205482a2fcd797047a5fdc01a0baa1bdfaf136386", code: "a\n~~~", }, }, }, { name: "test suggestion with wrong end (~)", arg: "~~~ suggestion\na\n```\n", want: []suggestion{ { checkSum: "83380dbcc26319cbdbb70c1ad11480c464cf731560a5d645afb727da33930611", code: "a\n```", }, }, }, { name: "test suggestion with not enough endmarker (`)", arg: "``` suggestion\na\n``\n", want: []suggestion{ { checkSum: "5b2b3107a7cceac969684464f39d300c8d1480b5fa300bc1b222c8e21db6c757", code: "a\n``", }, }, }, { name: "test suggestion with not enough endmarker (~, more than 3)", arg: "~~~~ suggestion\na\n~~~", want: []suggestion{ { checkSum: "862bb949147c31270cce026205482a2fcd797047a5fdc01a0baa1bdfaf136386", code: "a\n~~~", }, }, }, { name: "test suggestion with trailing invalid chars on endmarker (`)", arg: "``` suggestion\na\n```a\n", want: []suggestion{ { checkSum: "bd87ec5a4beda93c6912f0b786556f3a7c30772222dc65c104e2e60770492339", code: "a\n```a", }, }, }, { name: "test suggestion with trailing invalid chars on endmarker (~)", arg: "~~~ suggestion\na\n~~~a", want: []suggestion{ { checkSum: "07333da4c8a7348e4acd1a06566bb82d1a5f2a963e126158842308ec8b1d68f0", code: "a\n~~~a", }, }, }, { name: "test basic suggestion with text around(`)", arg: "adb\n``` suggestion\na\n```\nawef\n2r3", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, }, }, { name: "test basic suggestion with text around(~)", arg: "adb\n~~~ suggestion\na\n~~~\nawef\n2r3", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, }, }, { name: "test suggestion with spaces in markers (~)", arg: " ~~~ \t\tsuggestion \t\na\n ~~~ \t ", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, }, }, { name: "test suggestion with spaces in markers (`, more than 3)", arg: " ```` \t suggestion \t\t \na\n ```` \t ", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, }, }, { name: "test suggestion with too many end marker chars (`)", arg: "``` suggestion\na\n`````````", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, }, }, { name: "test suggestion with too many end marker chars (`)", arg: "~~~~~ suggestion\na\n~~~~~~~~~~~~", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, }, }, { name: "test suggestion that contains opposite marker (`)", arg: "``` suggestion\n~~~ suggestion\na\n~~~\n```", want: []suggestion{ { checkSum: "ed25a1606bf819448bf7e76fce9dbd2897fa5a379b67be74b5819ee521455783", code: "~~~ suggestion\na\n~~~", }, }, }, { name: "test suggestion that contains opposite marker (~)", arg: "~~~ suggestion\n``` suggestion\na\n```\n~~~", want: []suggestion{ { checkSum: "2463ad212ec8179e1f4d2a9ac35349b02e46bcba2173f6b05c9f73dfb4ca7ed9", code: "``` suggestion\na\n```", }, }, }, { name: "test suggestion that contains shorter marker (`)", arg: "```` suggestion\n``` suggestion\na\n```\n````", want: []suggestion{ { checkSum: "2463ad212ec8179e1f4d2a9ac35349b02e46bcba2173f6b05c9f73dfb4ca7ed9", code: "``` suggestion\na\n```", }, }, }, { name: "test suggestion that contains shorter marker (~)", arg: "~~~~ suggestion\n~~~ suggestion\na\n~~~\n~~~~", want: []suggestion{ { checkSum: "ed25a1606bf819448bf7e76fce9dbd2897fa5a379b67be74b5819ee521455783", code: "~~~ suggestion\na\n~~~", }, }, }, { name: "test multiple suggestions same marker (`)", arg: "``` suggestion\na\n```\nsomething``\n``` suggestion\nb\n```", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, { checkSum: "3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d", code: "b", }, }, }, { name: "test multiple suggestions same marker (~)", arg: "~~~ suggestion\na\n~~~\nsomething~~\n~~~ suggestion\nb\n~~~", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, { checkSum: "3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d", code: "b", }, }, }, { name: "test multiple suggestions different markder (`,~)", arg: "``` suggestion\na\n```\nsomething~~\n~~~ suggestion\nb\n~~~", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, { checkSum: "3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d", code: "b", }, }, }, { name: "test multiple suggestions last not ending (`,~)", arg: "``` suggestion\na\n```\nsomething~~\n~~~ suggestion\nb\n~~~\n\n``` suggestion\nc", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, { checkSum: "3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d", code: "b", }, { checkSum: "2e7d2c03a9507ae265ecf5b5356885a53393a2029d241394997265a1a25aefc6", code: "c", }, }, }, { name: "test with crlf and multiple (`,~)", arg: "abc\n``` suggestion\r\na\n```\r\n~~~ suggestion\nb\r\n~~~", want: []suggestion{ { checkSum: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", code: "a", }, { checkSum: "3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d", code: "b", }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := parseSuggestions(tt.arg) if !reflect.DeepEqual(got, tt.want) { t.Errorf("parseSuggestions() = %s, want %s", got, tt.want) } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/usergroup_reviewer_add.go
app/api/controller/pullreq/usergroup_reviewer_add.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 pullreq import ( "context" "errors" "fmt" "time" "github.com/harness/gitness/app/auth" events "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type UserGroupReviewerAddInput struct { UserGroupID int64 `json:"usergroup_id"` } // UserGroupReviewerAdd adds a new usergroup to the pull request in the usergroups db. func (c *Controller) UserGroupReviewerAdd( ctx context.Context, session *auth.Session, repoRef string, prNum int64, in *UserGroupReviewerAddInput, ) (*types.UserGroupReviewer, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return nil, fmt.Errorf("failed to find pull request by number: %w", err) } reviewers, err := c.reviewerStore.List(ctx, pr.ID) if err != nil { return nil, fmt.Errorf("failed to list reviewers: %w", err) } userGroup, err := c.userGroupStore.Find(ctx, in.UserGroupID) if err != nil { return nil, fmt.Errorf("failed to find user group: %w", err) } userIDs, err := c.userGroupService.ListUserIDsByGroupIDs(ctx, []int64{userGroup.ID}) if err != nil { return nil, fmt.Errorf("failed to list user ids by group id: %w", err) } reviewersMap := reviewersMap(reviewers) // Build user group reviewer decisions for SHA-aware logic userGroupReviewerDecisions := userGroupReviewerDecisions(userIDs, reviewersMap) // Use our established SHA-aware decision logic decision, userGroupSHA := determineUserGroupCompoundDecision(userGroupReviewerDecisions, pr.SourceSHA) userGroupReviewer, err := c.userGroupReviewerStore.Find(ctx, pr.ID, in.UserGroupID) if err != nil && !errors.Is(err, store.ErrResourceNotFound) { return nil, fmt.Errorf("failed to find user group reviewer: %w", err) } if userGroupReviewer != nil { addedBy, err := c.principalInfoCache.Get(ctx, userGroupReviewer.CreatedBy) if err != nil { return nil, fmt.Errorf("failed to get added by principal info: %w", err) } userGroupReviewer.AddedBy = *addedBy userGroupReviewer.UserGroup = *userGroup.ToUserGroupInfo() userGroupReviewer.Decision = decision userGroupReviewer.SHA = userGroupSHA userGroupReviewer.UserDecisions = userGroupReviewerDecisions return userGroupReviewer, nil } now := time.Now().UnixMilli() userGroupReviewer = &types.UserGroupReviewer{ PullReqID: pr.ID, UserGroupID: in.UserGroupID, CreatedBy: session.Principal.ID, Created: now, Updated: now, RepoID: repo.ID, UserGroup: *userGroup.ToUserGroupInfo(), AddedBy: *session.Principal.ToPrincipalInfo(), UserDecisions: userGroupReviewerDecisions, Decision: decision, SHA: userGroupSHA, } err = c.userGroupReviewerStore.Create(ctx, userGroupReviewer) if err != nil { return nil, fmt.Errorf("failed to create pull request reviewer: %w", err) } c.reportUserGroupReviewerAdded(ctx, &session.Principal, pr, userGroupReviewer.UserGroupID) err = func() error { if pr, err = c.pullreqStore.UpdateActivitySeq(ctx, pr); err != nil { return fmt.Errorf("failed to increment pull request activity sequence: %w", err) } payload := &types.PullRequestActivityPayloadUserGroupReviewerAdd{ UserGroupIDs: []int64{userGroupReviewer.UserGroupID}, ReviewerType: enum.PullReqReviewerTypeRequested, } metadata := &types.PullReqActivityMetadata{ Mentions: &types.PullReqActivityMentionsMetadata{ UserGroupIDs: []int64{userGroupReviewer.UserGroupID}, }, } if _, err := c.activityStore.CreateWithPayload( ctx, pr, session.Principal.ID, payload, metadata, ); err != nil { return err } return nil }() if err != nil { log.Ctx(ctx).Err(err).Msgf( "failed to write pull request activity after reviewer addition: %s", err, ) } return userGroupReviewer, nil } func (c *Controller) reportUserGroupReviewerAdded( ctx context.Context, principal *types.Principal, pr *types.PullReq, userGroupReviewerID int64, ) { c.eventReporter.UserGroupReviewerAdded( ctx, &events.UserGroupReviewerAddedPayload{ Base: eventBase(pr, principal), UserGroupReviewerID: userGroupReviewerID, }, ) } func reviewersMap(reviewers []*types.PullReqReviewer) map[int64]*types.PullReqReviewer { reviewersMap := make(map[int64]*types.PullReqReviewer, len(reviewers)) for _, reviewer := range reviewers { reviewersMap[reviewer.PrincipalID] = reviewer } return reviewersMap }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/pr_diff.go
app/api/controller/pullreq/pr_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 pullreq import ( "context" "fmt" "io" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" gittypes "github.com/harness/gitness/git/api" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // RawDiff writes raw git diff to writer w. func (c *Controller) RawDiff( ctx context.Context, w io.Writer, session *auth.Session, repoRef string, pullreqNum int64, setSHAs func(sourceSHA, mergeBaseSHA string), files ...gittypes.FileDiffRequest, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return fmt.Errorf("failed to acquire access to target repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return fmt.Errorf("failed to get pull request by number: %w", err) } if setSHAs != nil { setSHAs(pr.SourceSHA, pr.MergeBaseSHA) } return c.git.RawDiff(ctx, w, &git.DiffParams{ ReadParams: git.CreateReadParams(repo), BaseRef: pr.MergeBaseSHA, HeadRef: pr.SourceSHA, MergeBase: true, }, files...) } func (c *Controller) Diff( ctx context.Context, session *auth.Session, repoRef string, pullreqNum int64, setSHAs func(sourceSHA, mergeBaseSHA string), includePatch bool, ignoreWhitespace bool, files ...gittypes.FileDiffRequest, ) (types.Stream[*git.FileDiff], error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to target repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) if err != nil { return nil, fmt.Errorf("failed to get pull request by number: %w", err) } if setSHAs != nil { setSHAs(pr.SourceSHA, pr.MergeBaseSHA) } reader := git.NewStreamReader(c.git.Diff(ctx, &git.DiffParams{ ReadParams: git.CreateReadParams(repo), BaseRef: pr.MergeBaseSHA, HeadRef: pr.SourceSHA, MergeBase: true, IncludePatch: includePatch, IgnoreWhitespace: ignoreWhitespace, }, files...)) return reader, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/pr_list.go
app/api/controller/pullreq/pr_list.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // List returns a list of pull requests from the provided repository. func (c *Controller) List( ctx context.Context, session *auth.Session, repoRef string, filter *types.PullReqFilter, ) ([]*types.PullReq, int64, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to target repo: %w", err) } if filter.SourceRepoRef == repoRef { filter.SourceRepoID = repo.ID } else if filter.SourceRepoRef != "" { var sourceRepo *types.RepositoryCore sourceRepo, err = c.getRepoCheckAccess(ctx, session, filter.SourceRepoRef, enum.PermissionRepoView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to source repo: %w", err) } filter.SourceRepoID = sourceRepo.ID } var list []*types.PullReq var count int64 filter.TargetRepoID = repo.ID err = c.tx.WithTx(ctx, func(ctx context.Context) error { list, err = c.pullreqStore.List(ctx, filter) if err != nil { return fmt.Errorf("failed to list pull requests: %w", err) } err := c.labelSvc.BackfillMany(ctx, list) if err != nil { return fmt.Errorf("failed to backfill labels assigned to pull requests: %w", err) } if filter.Page == 1 && len(list) < filter.Size { count = int64(len(list)) return nil } count, err = c.pullreqStore.Count(ctx, filter) if err != nil { return fmt.Errorf("failed to count pull requests: %w", err) } return nil }, dbtx.TxDefaultReadOnly) if err != nil { return nil, 0, err } if err := c.pullreqListService.BackfillMetadataForRepo(ctx, repo, list, filter.PullReqMetadataOptions); err != nil { return nil, 0, fmt.Errorf("failed to backfill metadata for pull requests: %w", err) } return list, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/activity_list.go
app/api/controller/pullreq/activity_list.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ActivityList returns a list of pull request activities // from the provided repository and pull request number. func (c *Controller) ActivityList( ctx context.Context, session *auth.Session, repoRef string, prNum int64, filter *types.PullReqActivityFilter, ) ([]*types.PullReqActivity, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return nil, fmt.Errorf("failed to find pull request by number: %w", err) } list, err := c.activityStore.List(ctx, pr.ID, filter) if err != nil { return nil, fmt.Errorf("failed to list pull requests activities: %w", err) } for _, act := range list { if act.Metadata == nil || act.Metadata.Mentions == nil { continue } if act.Metadata.Mentions.IDs != nil { mentions, err := c.principalInfoCache.Map(ctx, act.Metadata.Mentions.IDs) if err != nil { return nil, fmt.Errorf("failed to fetch activity mentions from principalInfoView: %w", err) } act.Mentions = mentions } if act.Metadata.Mentions.UserGroupIDs != nil { groups, err := c.userGroupStore.Map(ctx, act.Metadata.Mentions.UserGroupIDs) if err != nil { return nil, fmt.Errorf("failed to fetch activity mentions from userGroupStore: %w", err) } groupInfoMentions := make(map[int64]*types.UserGroupInfo, len(groups)) for id, g := range groups { if g != nil { groupInfoMentions[id] = g.ToUserGroupInfo() } } act.GroupMentions = groupInfoMentions } } list = removeDeletedComments(list) return list, nil } func allCommentsDeleted(comments []*types.PullReqActivity) bool { for _, comment := range comments { if comment.Deleted == nil { return false } } return true } // removeDeletedComments removes all (ordinary comment and change comment) threads // (the top level comment and all replies to it), but only if all comments // in the thread are deleted. Just one non-deleted reply in a thread will cause // the entire thread to be included in the resulting list. func removeDeletedComments(list []*types.PullReqActivity) []*types.PullReqActivity { var ( threadIdx int threadLen int listIdx int ) inspectThread := func() { if threadLen > 0 && !allCommentsDeleted(list[threadIdx:threadIdx+threadLen]) { copy(list[listIdx:listIdx+threadLen], list[threadIdx:threadIdx+threadLen]) listIdx += threadLen } threadLen = 0 } for i, act := range list { if act.Deleted != nil { act.Text = "" // return deleted comments, but remove their content } if act.Kind == enum.PullReqActivityKindComment || act.Kind == enum.PullReqActivityKindChangeComment { if threadLen == 0 || list[threadIdx].Order != act.Order { inspectThread() threadIdx = i threadLen = 1 } else { threadLen++ } continue } inspectThread() list[listIdx] = act listIdx++ } inspectThread() return list[:listIdx] }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pullreq/file_view_delete.go
app/api/controller/pullreq/file_view_delete.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 pullreq import ( "context" "fmt" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) // FileViewDelete removes a file from being marked as viewed. func (c *Controller) FileViewDelete( ctx context.Context, session *auth.Session, repoRef string, prNum int64, filePath string, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return fmt.Errorf("failed to acquire access to repo: %w", err) } pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return fmt.Errorf("failed to find pull request by number: %w", err) } if filePath == "" { return usererror.BadRequest("File path can't be empty") } err = c.fileViewStore.DeleteByFileForPrincipal(ctx, pr.ID, session.Principal.ID, filePath) if err != nil { return fmt.Errorf("failed to delete file view entry in db: %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/app/api/controller/pullreq/comment_create.go
app/api/controller/pullreq/comment_create.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 pullreq import ( "context" "fmt" "strings" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" events "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type CommentCreateInput struct { // ParentID is set only for replies ParentID int64 `json:"parent_id"` // Text is comment text Text string `json:"text"` // Used only for code comments TargetCommitSHA string `json:"target_commit_sha"` SourceCommitSHA string `json:"source_commit_sha"` Path string `json:"path"` LineStart int `json:"line_start"` LineStartNew bool `json:"line_start_new"` LineEnd int `json:"line_end"` LineEndNew bool `json:"line_end_new"` } func (in *CommentCreateInput) IsReply() bool { return in.ParentID != 0 } func (in *CommentCreateInput) IsCodeComment() bool { return in.SourceCommitSHA != "" } func (in *CommentCreateInput) Sanitize() error { in.Text = strings.TrimSpace(in.Text) if err := validateComment(in.Text); err != nil { return err } if in.SourceCommitSHA == "" && in.TargetCommitSHA == "" { return nil // not a code comment } if in.SourceCommitSHA == "" || in.TargetCommitSHA == "" { return usererror.BadRequest("For code comments source commit SHA and target commit SHA must be provided") } if in.ParentID != 0 { return usererror.BadRequest("Can't create a reply that is a code comment") } if in.Path == "" { return usererror.BadRequest("Code comment requires file path") } if in.LineStart <= 0 || in.LineEnd <= 0 { return usererror.BadRequest("Code comments require line numbers") } if in.LineStartNew && !in.LineEndNew || !in.LineStartNew && in.LineEndNew { return usererror.BadRequest("Code block must start and end on the same side") } return nil } // CommentCreate creates a new pull request comment (pull request activity, type=comment/code-comment). // //nolint:gocognit // refactor if needed func (c *Controller) CommentCreate( ctx context.Context, session *auth.Session, repoRef string, prNum int64, in *CommentCreateInput, ) (*types.PullReqActivity, error) { if err := in.Sanitize(); err != nil { return nil, err } repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } var pr *types.PullReq pr, err = c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return nil, fmt.Errorf("failed to find pull request by number: %w", err) } var parentAct *types.PullReqActivity if in.IsReply() { parentAct, err = c.checkIsReplyable(ctx, pr, in.ParentID) if err != nil { return nil, fmt.Errorf("failed to verify reply: %w", err) } } // fetch code snippet from git for code comments var cut git.DiffCutOutput if in.IsCodeComment() { cut, err = c.fetchDiffCut(ctx, repo, in) if err != nil { return nil, err } } // generate all metadata updates var metadataUpdates []types.PullReqActivityMetadataUpdate metadataUpdates, principalInfos, err := c.appendMetadataUpdateForMentions( ctx, metadataUpdates, in.Text) if err != nil { return nil, fmt.Errorf("failed to update metadata for mentions: %w", err) } // suggestion metadata in case of code comments or code comment replies (don't restrict to either side for now). if in.IsCodeComment() || (in.IsReply() && parentAct.IsValidCodeComment()) { metadataUpdates = appendMetadataUpdateForSuggestions(metadataUpdates, in.Text) } var act *types.PullReqActivity err = controller.TxOptLock(ctx, c.tx, func(ctx context.Context) error { var err error if pr == nil { // the pull request was fetched before the transaction, we re-fetch it in case of the version conflict error pr, err = c.pullreqStore.FindByNumber(ctx, repo.ID, prNum) if err != nil { return fmt.Errorf("failed to find pull request by number: %w", err) } } act = getCommentActivity(session, pr, in, metadataUpdates) // In the switch the pull request activity (the code comment) // is written to the DB (as code comment, a reply, or ordinary comment). switch { case in.IsCodeComment(): setAsCodeComment(act, cut, in.Path, in.SourceCommitSHA) _ = act.SetPayload(&types.PullRequestActivityPayloadCodeComment{ Title: cut.LinesHeader, Lines: cut.Lines, LineStartNew: in.LineStartNew, LineEndNew: in.LineEndNew, }) err = c.writeActivity(ctx, pr, act) case in.IsReply(): act.ParentID = &parentAct.ID act.Kind = parentAct.Kind _ = act.SetPayload(types.PullRequestActivityPayloadComment{}) err = c.writeReplyActivity(ctx, parentAct, act) default: // top level comment _ = act.SetPayload(types.PullRequestActivityPayloadComment{}) err = c.writeActivity(ctx, pr, act) } if err != nil { return fmt.Errorf("failed to write pull request comment: %w", err) } pr.CommentCount++ if act.IsBlocking() { pr.UnresolvedCount++ } err = c.pullreqStore.Update(ctx, pr) if err != nil { return fmt.Errorf("failed to increment pull request comment counters: %w", err) } return nil }, controller.TxOptionResetFunc(func() { pr = nil // on the version conflict error force re-fetch of the pull request })) if err != nil { return nil, err } // Populate activity mentions (used only for response purposes). act.Mentions = principalInfos if in.IsCodeComment() { // Migrate the comment if necessary... Note: we still need to return the code comment as is. c.migrateCodeComment(ctx, repo, pr, in, act.AsCodeComment(), cut) } c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypePullReqUpdated, pr) // publish event for all comments if act.Type == enum.PullReqActivityTypeComment || act.Type == enum.PullReqActivityTypeCodeComment { c.reportCommentCreated( ctx, pr, session.Principal.ID, act.ID, act.IsReply(), ) } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeCreatePRComment, Principal: session.Principal.ToPrincipalInfo(), Path: repo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, instrument.PropertyPullRequestID: pr.Number, instrument.PropertyCommentIsReplied: in.IsReply(), instrument.PropertyCommentContainsSuggestion: len(parseSuggestions(in.Text)) > 0, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for create pull request comment operation: %s", err) } return act, nil } func (c *Controller) checkIsReplyable( ctx context.Context, pr *types.PullReq, parentID int64, ) (*types.PullReqActivity, error) { // make sure the parent comment exists, belongs to the same PR and isn't itself a reply parentAct, err := c.activityStore.Find(ctx, parentID) if errors.Is(err, store.ErrResourceNotFound) || parentAct == nil { return nil, usererror.BadRequest("Parent pull request activity not found.") } if err != nil { return nil, fmt.Errorf("failed to find parent pull request activity: %w", err) } if parentAct.PullReqID != pr.ID || parentAct.RepoID != pr.TargetRepoID { return nil, usererror.BadRequest("Parent pull request activity doesn't belong to the same pull request.") } if !parentAct.IsReplyable() { return nil, usererror.BadRequest("Can't create a reply to the specified entry.") } return parentAct, nil } // writeActivity updates the PR's activity sequence number (using the optimistic locking mechanism), // sets the correct Order value and writes the activity to the database. // Even if the writing fails, the updating of the sequence number can succeed. func (c *Controller) writeActivity(ctx context.Context, pr *types.PullReq, act *types.PullReqActivity) error { prUpd, err := c.pullreqStore.UpdateActivitySeq(ctx, pr) if err != nil { return fmt.Errorf("failed to get pull request activity number: %w", err) } *pr = *prUpd // update the pull request object act.Order = prUpd.ActivitySeq err = c.activityStore.Create(ctx, act) if err != nil { return fmt.Errorf("failed to create pull request activity: %w", err) } return nil } // writeReplyActivity updates the parent activity's reply sequence number (using the optimistic locking mechanism), // sets the correct Order and SubOrder values and writes the activity to the database. // Even if the writing fails, the updating of the sequence number can succeed. func (c *Controller) writeReplyActivity(ctx context.Context, parent, act *types.PullReqActivity) error { parentUpd, err := c.activityStore.UpdateOptLock(ctx, parent, func(act *types.PullReqActivity) error { act.ReplySeq++ return nil }) if err != nil { return fmt.Errorf("failed to get pull request activity number: %w", err) } *parent = *parentUpd // update the parent pull request activity object act.Order = parentUpd.Order act.SubOrder = parentUpd.ReplySeq err = c.activityStore.Create(ctx, act) if err != nil { return fmt.Errorf("failed to create pull request activity: %w", err) } return nil } func getCommentActivity( session *auth.Session, pr *types.PullReq, in *CommentCreateInput, metadataUpdates []types.PullReqActivityMetadataUpdate, ) *types.PullReqActivity { now := time.Now().UnixMilli() act := &types.PullReqActivity{ ID: 0, // Will be populated in the data layer Version: 0, CreatedBy: session.Principal.ID, Created: now, Updated: now, Edited: now, Deleted: nil, ParentID: nil, // Will be filled in CommentCreate RepoID: pr.TargetRepoID, PullReqID: pr.ID, Order: 0, // Will be filled in writeActivity/writeReplyActivity SubOrder: 0, // Will be filled in writeReplyActivity ReplySeq: 0, Type: enum.PullReqActivityTypeComment, Kind: enum.PullReqActivityKindComment, Text: in.Text, Metadata: nil, ResolvedBy: nil, Resolved: nil, Author: *session.Principal.ToPrincipalInfo(), } act.UpdateMetadata(metadataUpdates...) return act } func setAsCodeComment(a *types.PullReqActivity, cut git.DiffCutOutput, path, sourceCommitSHA string) { var falseBool bool a.Type = enum.PullReqActivityTypeCodeComment a.Kind = enum.PullReqActivityKindChangeComment a.CodeComment = &types.CodeCommentFields{ Outdated: falseBool, MergeBaseSHA: cut.MergeBaseSHA.String(), SourceSHA: sourceCommitSHA, Path: path, LineNew: cut.Header.NewLine, SpanNew: cut.Header.NewSpan, LineOld: cut.Header.OldLine, SpanOld: cut.Header.OldSpan, } } func (c *Controller) fetchDiffCut( ctx context.Context, repo *types.RepositoryCore, in *CommentCreateInput, ) (git.DiffCutOutput, error) { // maxDiffLineCount restricts the total length of a code comment diff to 1000 lines. // TODO: This can still lead to wrong code comments in cases like a large file being replaced by one line. const maxDiffLineCount = 1000 cut, err := c.git.DiffCut(ctx, &git.DiffCutParams{ ReadParams: git.ReadParams{RepoUID: repo.GitUID}, SourceCommitSHA: in.SourceCommitSHA, TargetCommitSHA: in.TargetCommitSHA, Path: in.Path, LineStart: in.LineStart, LineStartNew: in.LineStartNew, LineEnd: in.LineEnd, LineEndNew: in.LineEndNew, LineLimit: maxDiffLineCount, }) if errors.AsStatus(err) == errors.StatusNotFound { return git.DiffCutOutput{}, usererror.BadRequest(errors.Message(err)) } if err != nil { return git.DiffCutOutput{}, fmt.Errorf("failed to fetch git diff cut: %w", err) } return cut, nil } func (c *Controller) migrateCodeComment( ctx context.Context, repo *types.RepositoryCore, pr *types.PullReq, in *CommentCreateInput, cc *types.CodeComment, cut git.DiffCutOutput, ) { needsNewLineMigrate := in.SourceCommitSHA != pr.SourceSHA needsOldLineMigrate := cut.MergeBaseSHA.String() != pr.MergeBaseSHA if !needsNewLineMigrate && !needsOldLineMigrate { return } comments := []*types.CodeComment{cc} if needsNewLineMigrate { c.codeCommentMigrator.MigrateNew(ctx, repo.GitUID, pr.SourceSHA, comments) } if needsOldLineMigrate { c.codeCommentMigrator.MigrateOld(ctx, repo.GitUID, pr.MergeBaseSHA, comments) } if errMigrateUpdate := c.codeCommentView.UpdateAll(ctx, comments); errMigrateUpdate != nil { // non-critical error log.Ctx(ctx).Err(errMigrateUpdate). Msgf("failed to migrate code comment to the latest source/merge-base commit SHA") } } func (c *Controller) reportCommentCreated( ctx context.Context, pr *types.PullReq, principalID int64, actID int64, isReply bool, ) { c.eventReporter.CommentCreated(ctx, &events.CommentCreatedPayload{ Base: events.Base{ PullReqID: pr.ID, SourceRepoID: pr.SourceRepoID, TargetRepoID: pr.TargetRepoID, PrincipalID: principalID, Number: pr.Number, }, ActivityID: actID, SourceSHA: pr.SourceSHA, IsReply: isReply, }) } func appendMetadataUpdateForSuggestions( updates []types.PullReqActivityMetadataUpdate, comment string, ) []types.PullReqActivityMetadataUpdate { suggestions := parseSuggestions(comment) return append( updates, types.WithPullReqActivitySuggestionsMetadataUpdate( func(m *types.PullReqActivitySuggestionsMetadata) { m.CheckSums = make([]string, len(suggestions)) for i := range suggestions { m.CheckSums[i] = suggestions[i].checkSum } }), ) } func (c *Controller) appendMetadataUpdateForMentions( ctx context.Context, updates []types.PullReqActivityMetadataUpdate, comment string, ) ([]types.PullReqActivityMetadataUpdate, map[int64]*types.PrincipalInfo, error) { principalInfos, err := c.processMentions(ctx, comment) if err != nil { return nil, map[int64]*types.PrincipalInfo{}, err } ids := make([]int64, len(principalInfos)) i := 0 for id := range principalInfos { ids[i] = id i++ } return append( updates, types.WithPullReqActivityMentionsMetadataUpdate( func(m *types.PullReqActivityMentionsMetadata) { m.IDs = ids }), ), principalInfos, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/preprocessor.go
app/api/controller/webhook/preprocessor.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 webhook import ( "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type Preprocessor interface { PreprocessCreateInput( enum.PrincipalType, *types.WebhookCreateInput, *types.WebhookSignatureMetadata, ) (enum.WebhookType, error) PreprocessUpdateInput( enum.PrincipalType, *types.WebhookUpdateInput, *types.WebhookSignatureMetadata, ) (enum.WebhookType, error) PreprocessFilter(enum.PrincipalType, *types.WebhookFilter) IsInternalCall(enum.PrincipalType) bool } type NoopPreprocessor struct { } // PreprocessCreateInput always return false for internal. func (p NoopPreprocessor) PreprocessCreateInput( enum.PrincipalType, *types.WebhookCreateInput, *types.WebhookSignatureMetadata, ) (enum.WebhookType, error) { return enum.WebhookTypeExternal, nil } // PreprocessUpdateInput always return false for internal. func (p NoopPreprocessor) PreprocessUpdateInput( enum.PrincipalType, *types.WebhookUpdateInput, *types.WebhookSignatureMetadata, ) (enum.WebhookType, error) { return enum.WebhookTypeExternal, nil } func (p NoopPreprocessor) PreprocessFilter(_ enum.PrincipalType, filter *types.WebhookFilter) { if filter.Order == enum.OrderDefault { filter.Order = enum.OrderAsc } // always skip internal for requests from handler filter.SkipInternal = true } func (p NoopPreprocessor) IsInternalCall(enum.PrincipalType) bool { return false }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/space_list_executions.go
app/api/controller/webhook/space_list_executions.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListExecutionsSpace returns the executions of the webhook. func (c *Controller) ListExecutionsSpace( ctx context.Context, session *auth.Session, spaceRef string, webhookIdentifier string, filter *types.WebhookExecutionFilter, ) ([]*types.WebhookExecution, int64, error) { space, err := c.getSpaceCheckAccess(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to space: %w", err) } return c.webhookService.ListExecutions( ctx, space.ID, enum.WebhookParentSpace, webhookIdentifier, filter) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/space_retrigger_execution.go
app/api/controller/webhook/space_retrigger_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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" webhooksservice "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // RetriggerExecutionSpace retriggers an existing webhook execution. func (c *Controller) RetriggerExecutionSpace( ctx context.Context, session *auth.Session, spaceRef string, webhookIdentifier string, webhookExecutionID int64, ) (*types.WebhookExecution, error) { space, err := c.getSpaceCheckAccess(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } executionCore, err := c.webhookService.RetriggerExecution( ctx, space.ID, enum.WebhookParentSpace, webhookIdentifier, webhookExecutionID) if err != nil { return nil, err } execution := webhooksservice.CoreWebhookExecutionToGitnessWebhookExecution(executionCore) return execution, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/space_create.go
app/api/controller/webhook/space_create.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // CreateSpace creates a new webhook. func (c *Controller) CreateSpace( ctx context.Context, session *auth.Session, spaceRef string, in *types.WebhookCreateInput, signatureData *types.WebhookSignatureMetadata, ) (*types.Webhook, error) { space, err := c.getSpaceCheckAccess(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } internal, err := c.preprocessor.PreprocessCreateInput(session.Principal.Type, in, signatureData) if err != nil { return nil, fmt.Errorf("failed to preprocess create input: %w", err) } hook, err := c.webhookService.Create( ctx, &session.Principal, internal, webhook.ParentResource{ ID: space.ID, Identifier: space.Identifier, Type: enum.WebhookParentSpace, Path: space.Path, }, in) if err != nil { return nil, fmt.Errorf("failed to create webhook: %w", err) } return hook, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/wire.go
app/api/controller/webhook/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 webhook import ( "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/encrypt" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideController, ) func ProvideController(authorizer authz.Authorizer, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder, webhookService *webhook.Service, encrypter encrypt.Encrypter, preprocessor Preprocessor, ) *Controller { return NewController( authorizer, spaceFinder, repoFinder, webhookService, encrypter, preprocessor) } func ProvidePreprocessor() Preprocessor { return NoopPreprocessor{} }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/repo_list_executions.go
app/api/controller/webhook/repo_list_executions.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListExecutionsRepo returns the executions of the webhook. func (c *Controller) ListExecutionsRepo( ctx context.Context, session *auth.Session, repoRef string, webhookIdentifier string, filter *types.WebhookExecutionFilter, ) ([]*types.WebhookExecution, int64, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to the repo: %w", err) } return c.webhookService.ListExecutions( ctx, repo.ID, enum.WebhookParentRepo, webhookIdentifier, filter) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/space_list.go
app/api/controller/webhook/space_list.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListSpace returns the webhooks from the provided space. func (c *Controller) ListSpace( ctx context.Context, session *auth.Session, spaceRef string, inherited bool, filter *types.WebhookFilter, ) ([]*types.Webhook, int64, error) { space, err := c.getSpaceCheckAccess(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to space: %w", err) } c.preprocessor.PreprocessFilter(session.Principal.Type, filter) return c.webhookService.List(ctx, space.ID, enum.WebhookParentSpace, inherited, filter) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/space_find_execution.go
app/api/controller/webhook/space_find_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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // FindExecutionSpace finds a webhook execution. func (c *Controller) FindExecutionSpace( ctx context.Context, session *auth.Session, spaceRef string, webhookIdentifier string, webhookExecutionID int64, ) (*types.WebhookExecution, error) { space, err := c.getSpaceCheckAccess(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } return c.webhookService.FindExecution( ctx, space.ID, enum.WebhookParentSpace, webhookIdentifier, webhookExecutionID) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/repo_update.go
app/api/controller/webhook/repo_update.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // UpdateRepo updates an existing webhook. func (c *Controller) UpdateRepo( ctx context.Context, session *auth.Session, repoRef string, webhookIdentifier string, in *types.WebhookUpdateInput, signatureData *types.WebhookSignatureMetadata, ) (*types.Webhook, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to the repo: %w", err) } typ, err := c.preprocessor.PreprocessUpdateInput(session.Principal.Type, in, signatureData) if err != nil { return nil, fmt.Errorf("failed to preprocess update input: %w", err) } return c.webhookService.Update( ctx, &session.Principal, webhookIdentifier, typ, webhook.ParentResource{ ID: repo.ID, Identifier: repo.Identifier, Type: enum.WebhookParentRepo, Path: paths.Parent(repo.Path), }, in) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/repo_find.go
app/api/controller/webhook/repo_find.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // FindRepo finds a webhook from the provided repository. func (c *Controller) FindRepo( ctx context.Context, session *auth.Session, repoRef string, webhookIdentifier string, ) (*types.Webhook, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to the repo: %w", err) } return c.webhookService.Find(ctx, repo.ID, enum.WebhookParentRepo, webhookIdentifier) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/space_update.go
app/api/controller/webhook/space_update.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // UpdateSpace updates an existing webhook. func (c *Controller) UpdateSpace( ctx context.Context, session *auth.Session, spaceRef string, webhookIdentifier string, in *types.WebhookUpdateInput, signatureData *types.WebhookSignatureMetadata, ) (*types.Webhook, error) { space, err := c.getSpaceCheckAccess(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } typ, err := c.preprocessor.PreprocessUpdateInput(session.Principal.Type, in, signatureData) if err != nil { return nil, fmt.Errorf("failed to preprocess update input: %w", err) } return c.webhookService.Update( ctx, &session.Principal, webhookIdentifier, typ, webhook.ParentResource{ ID: space.ID, Identifier: space.Identifier, Type: enum.WebhookParentSpace, Path: space.Path, }, in, ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/repo_retrigger_execution.go
app/api/controller/webhook/repo_retrigger_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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" webhooksservice "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // RetriggerExecutionRepo retriggers an existing webhook execution. func (c *Controller) RetriggerExecutionRepo( ctx context.Context, session *auth.Session, repoRef string, webhookIdentifier string, webhookExecutionID int64, ) (*types.WebhookExecution, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to the repo: %w", err) } executionCore, err := c.webhookService.RetriggerExecution( ctx, repo.ID, enum.WebhookParentRepo, webhookIdentifier, webhookExecutionID) if err != nil { return nil, err } execution := webhooksservice.CoreWebhookExecutionToGitnessWebhookExecution(executionCore) return execution, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/repo_create.go
app/api/controller/webhook/repo_create.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // CreateRepo creates a new repo webhook. func (c *Controller) CreateRepo( ctx context.Context, session *auth.Session, repoRef string, in *types.WebhookCreateInput, signatureData *types.WebhookSignatureMetadata, ) (*types.Webhook, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to the repo: %w", err) } typ, err := c.preprocessor.PreprocessCreateInput(session.Principal.Type, in, signatureData) if err != nil { return nil, fmt.Errorf("failed to preprocess create input: %w", err) } hook, err := c.webhookService.Create( ctx, &session.Principal, typ, webhook.ParentResource{ ID: repo.ID, Identifier: repo.Identifier, Type: enum.WebhookParentRepo, Path: paths.Parent(repo.Path), }, in, ) if err != nil { return nil, fmt.Errorf("failed to create webhook: %w", err) } return hook, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/space_delete.go
app/api/controller/webhook/space_delete.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/types/enum" ) // DeleteSpace deletes an existing webhook. func (c *Controller) DeleteSpace( ctx context.Context, session *auth.Session, spaceRef string, webhookIdentifier string, ) error { space, err := c.getSpaceCheckAccess(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return fmt.Errorf("failed to acquire access to space: %w", err) } return c.webhookService.Delete( ctx, &session.Principal, webhookIdentifier, webhook.ParentResource{ ID: space.ID, Identifier: space.Identifier, Type: enum.WebhookParentSpace, Path: space.Path, }, c.preprocessor.IsInternalCall(session.Principal.Type), ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/repo_list.go
app/api/controller/webhook/repo_list.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListRepo returns the webhooks from the provided repository. func (c *Controller) ListRepo( ctx context.Context, session *auth.Session, repoRef string, inherited bool, filter *types.WebhookFilter, ) ([]*types.Webhook, int64, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to the repo: %w", err) } c.preprocessor.PreprocessFilter(session.Principal.Type, filter) return c.webhookService.List(ctx, repo.ID, enum.WebhookParentRepo, inherited, filter) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/repo_delete.go
app/api/controller/webhook/repo_delete.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/types/enum" ) // DeleteRepo deletes an existing webhook. func (c *Controller) DeleteRepo( ctx context.Context, session *auth.Session, repoRef string, webhookIdentifier string, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return fmt.Errorf("failed to acquire access to the repo: %w", err) } return c.webhookService.Delete( ctx, &session.Principal, webhookIdentifier, webhook.ParentResource{ ID: repo.ID, Identifier: repo.Identifier, Type: enum.WebhookParentRepo, Path: paths.Parent(repo.Path), }, c.preprocessor.IsInternalCall(session.Principal.Type), ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/controller.go
app/api/controller/webhook/controller.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 webhook import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/controller/space" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/encrypt" "github.com/harness/gitness/errors" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type Controller struct { authorizer authz.Authorizer spaceFinder refcache.SpaceFinder repoFinder refcache.RepoFinder webhookService *webhook.Service encrypter encrypt.Encrypter preprocessor Preprocessor } func NewController( authorizer authz.Authorizer, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder, webhookService *webhook.Service, encrypter encrypt.Encrypter, preprocessor Preprocessor, ) *Controller { return &Controller{ authorizer: authorizer, spaceFinder: spaceFinder, repoFinder: repoFinder, webhookService: webhookService, encrypter: encrypter, preprocessor: preprocessor, } } //nolint:unparam func (c *Controller) getRepoCheckAccess( ctx context.Context, session *auth.Session, repoRef string, reqPermission enum.Permission, allowedRepoStates ...enum.RepoState, ) (*types.RepositoryCore, error) { if repoRef == "" { return nil, errors.InvalidArgument("A valid repository reference must be provided.") } repo, err := c.repoFinder.FindByRef(ctx, repoRef) if err != nil { return nil, fmt.Errorf("failed to find repo: %w", err) } if err := apiauth.CheckRepoState(ctx, session, repo, reqPermission, allowedRepoStates...); err != nil { return nil, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, reqPermission); err != nil { return nil, fmt.Errorf("failed to verify authorization: %w", err) } return repo, nil } func (c *Controller) getSpaceCheckAccess( ctx context.Context, session *auth.Session, spaceRef string, permission enum.Permission, ) (*types.SpaceCore, error) { return space.GetSpaceCheckAuth(ctx, c.spaceFinder, c.authorizer, session, spaceRef, permission) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/space_find.go
app/api/controller/webhook/space_find.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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // FindSpace finds a webhook from the provided repository. func (c *Controller) FindSpace( ctx context.Context, session *auth.Session, spaceRef string, webhookIdentifier string, ) (*types.Webhook, error) { space, err := c.getSpaceCheckAccess(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } return c.webhookService.Find(ctx, space.ID, enum.WebhookParentSpace, webhookIdentifier) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/webhook/repo_find_execution.go
app/api/controller/webhook/repo_find_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 webhook import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // FindExecutionRepo finds a webhook execution. func (c *Controller) FindExecutionRepo( ctx context.Context, session *auth.Session, repoRef string, webhookIdentifier string, webhookExecutionID int64, ) (*types.WebhookExecution, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to the repo: %w", err) } return c.webhookService.FindExecution( ctx, repo.ID, enum.WebhookParentRepo, webhookIdentifier, webhookExecutionID) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/principal/wire.go
app/api/controller/principal/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 principal import ( "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/store" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideController, ) func ProvideController( principalStore store.PrincipalStore, authorizer authz.Authorizer, ) Controller { return newController(principalStore, authorizer) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/principal/types.go
app/api/controller/principal/types.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 principal type ( // CheckUsersInput is object for checking users existence during repo(s) import. CheckUsersInput struct { Emails []string `json:"emails"` } // CheckUsersOutput is output object for checking users existence. CheckUsersOutput struct { UnknownEmails []string `json:"unknown_emails"` } )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/principal/find_by_email.go
app/api/controller/principal/find_by_email.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 principal import ( "context" "errors" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c Controller) CheckExistenceByEmails( ctx context.Context, session *auth.Session, in *CheckUsersInput, ) (*CheckUsersOutput, error) { if err := apiauth.Check( ctx, c.authorizer, session, &types.Scope{}, &types.Resource{ Type: enum.ResourceTypeUser, }, enum.PermissionUserView, ); err != nil { return nil, err } unknownEmails := make([]string, 0) for _, email := range in.Emails { _, err := c.principalStore.FindUserByEmail(ctx, email) if errors.Is(err, store.ErrResourceNotFound) { unknownEmails = append(unknownEmails, email) continue } if err != nil { return nil, fmt.Errorf("encountered error in finding user by email: %w", err) } } return &CheckUsersOutput{UnknownEmails: unknownEmails}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/principal/find.go
app/api/controller/principal/find.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 principal import ( "context" "net/http" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c Controller) Find( ctx context.Context, session *auth.Session, principalID int64, ) (*types.PrincipalInfo, error) { principal, err := c.principalStore.Find(ctx, principalID) if err != nil { return nil, err } if principal.Type != enum.PrincipalTypeUser { return nil, usererror.Newf( http.StatusNotImplemented, "only user principals are supported currently.", ) } if err := apiauth.Check( ctx, c.authorizer, session, &types.Scope{}, &types.Resource{ Type: enum.ResourceTypeUser, }, enum.PermissionUserView, ); err != nil { return nil, err } return principal.ToPrincipalInfo(), nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/principal/list.go
app/api/controller/principal/list.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 principal import ( "context" "net/http" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c Controller) List( ctx context.Context, session *auth.Session, opts *types.PrincipalFilter, ) ([]*types.PrincipalInfo, error) { // only user search is supported right now! if len(opts.Types) != 1 || opts.Types[0] != enum.PrincipalTypeUser { return nil, usererror.Newf( http.StatusNotImplemented, "Only listing of users is supported at this moment (use query '%s=%s').", request.QueryParamType, enum.PrincipalTypeUser, ) } if err := apiauth.Check( ctx, c.authorizer, session, &types.Scope{}, &types.Resource{ Type: enum.ResourceTypeUser, }, enum.PermissionUserView, ); err != nil { return nil, err } principals, err := c.principalStore.List(ctx, opts) if err != nil { return nil, err } pInfoUsers := make([]*types.PrincipalInfo, len(principals)) for i := range principals { pInfoUsers[i] = principals[i].ToPrincipalInfo() } return pInfoUsers, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/principal/controller.go
app/api/controller/principal/controller.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 principal import ( "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/store" ) type Controller struct { principalStore store.PrincipalStore authorizer authz.Authorizer } func newController(principalStore store.PrincipalStore, authorizer authz.Authorizer) Controller { return Controller{ principalStore: principalStore, authorizer: authorizer, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/get_branch.go
app/api/controller/repo/get_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 repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // GetBranch gets a repo branch. func (c *Controller) GetBranch(ctx context.Context, session *auth.Session, repoRef string, branchName string, options types.BranchMetadataOptions, ) (*types.BranchExtended, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } rpcOut, err := c.git.GetBranch(ctx, &git.GetBranchParams{ ReadParams: git.CreateReadParams(repo), BranchName: branchName, }) if err != nil { return nil, fmt.Errorf("failed to get branch: %w", err) } metadata, err := c.collectBranchMetadata(ctx, repo, []git.Branch{rpcOut.Branch}, options) if err != nil { return nil, fmt.Errorf("fail to collect branch metadata: %w", err) } branch, err := controller.MapBranch(rpcOut.Branch) if err != nil { return nil, fmt.Errorf("failed to map branch: %w", err) } branchExtended := &types.BranchExtended{ Branch: branch, IsDefault: branchName == repo.DefaultBranch, } metadata.apply(0, branchExtended) return branchExtended, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/label_value_define.go
app/api/controller/repo/label_value_define.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 repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // DefineLabelValue defines a new label value for the specified repository. func (c *Controller) DefineLabelValue( ctx context.Context, session *auth.Session, repoRef string, key string, in *types.DefineValueInput, ) (*types.LabelValue, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } if err := in.Sanitize(); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } label, err := c.labelSvc.Find(ctx, nil, &repo.ID, key) if err != nil { return nil, fmt.Errorf("failed to find repo label: %w", err) } value, err := c.labelSvc.DefineValue(ctx, session.Principal.ID, label.ID, in) if err != nil { return nil, fmt.Errorf("failed to create repo label value: %w", err) } return value, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/blame.go
app/api/controller/repo/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 repo import ( "context" "strings" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c *Controller) Blame(ctx context.Context, session *auth.Session, repoRef, gitRef, path string, lineFrom, lineTo int, ) (types.Stream[*git.BlamePart], error) { path = strings.TrimSpace(path) if path == "" { return nil, usererror.BadRequest("File path needs to specified.") } if lineTo > 0 && lineFrom > lineTo { return nil, usererror.BadRequest("Line range must be valid.") } repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } if gitRef == "" { gitRef = repo.DefaultBranch } reader := git.NewStreamReader( c.git.Blame(ctx, &git.BlameParams{ ReadParams: git.CreateReadParams(repo), GitRef: gitRef, Path: path, LineFrom: lineFrom, LineTo: lineTo, })) return reader, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/squash.go
app/api/controller/repo/squash.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 repo import ( "context" "fmt" "strings" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/git" gitenum "github.com/harness/gitness/git/enum" "github.com/harness/gitness/git/parser" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type SquashInput struct { BaseBranch string `json:"base_branch"` BaseCommitSHA sha.SHA `json:"base_commit_sha"` HeadBranch string `json:"head_branch"` HeadCommitSHA sha.SHA `json:"head_commit_sha"` Title string `json:"title"` Message string `json:"message"` DryRun bool `json:"dry_run"` DryRunRules bool `json:"dry_run_rules"` BypassRules bool `json:"bypass_rules"` } func (in *SquashInput) validate() error { if in.BaseBranch == "" && in.BaseCommitSHA.IsEmpty() { return usererror.BadRequest("Either base branch or base commit SHA name must be provided") } if in.HeadBranch == "" { return usererror.BadRequest("Head branch name must be provided") } if in.HeadCommitSHA.IsEmpty() { return usererror.BadRequest("Head branch commit SHA must be provided") } // cleanup title / message (NOTE: git doesn't support white space only) in.Title = strings.TrimSpace(in.Title) in.Message = strings.TrimSpace(in.Message) return nil } // Squash squashes all commits since merge-base to the latest commit of the base branch. // This operation alters history of the base branch and therefore is considered a force push. // //nolint:gocognit func (c *Controller) Squash( ctx context.Context, session *auth.Session, repoRef string, in *SquashInput, ) (*types.SquashResponse, *types.MergeViolations, error) { if err := in.validate(); err != nil { return nil, nil, err } repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return nil, nil, fmt.Errorf("failed to acquire access to repo: %w", err) } protectionRules, isRepoOwner, err := c.fetchBranchRules(ctx, session, repo) if err != nil { return nil, nil, fmt.Errorf("failed to fetch rules: %w", err) } violations, err := protectionRules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: in.BypassRules, IsRepoOwner: isRepoOwner, Repo: repo, RefAction: protection.RefActionUpdateForce, RefType: protection.RefTypeBranch, RefNames: []string{in.HeadBranch}, }) if err != nil { return nil, nil, fmt.Errorf("failed to verify protection rules: %w", err) } if in.DryRunRules { // DryRunRules is true: Just return rule violations and don't squash commits. return &types.SquashResponse{ RuleViolations: violations, DryRunRules: true, }, nil, nil } if protection.IsCritical(violations) { return nil, &types.MergeViolations{ RuleViolations: violations, Message: protection.GenerateErrorMessageForBlockingViolations(violations), }, nil } readParams := git.CreateReadParams(repo) headBranch, err := c.git.GetBranch(ctx, &git.GetBranchParams{ ReadParams: readParams, BranchName: in.HeadBranch, }) if err != nil { return nil, nil, fmt.Errorf("failed to get head branch: %w", err) } if !headBranch.Branch.SHA.Equal(in.HeadCommitSHA) { return nil, nil, usererror.BadRequestf("The commit %s isn't the latest commit on the branch %s", in.HeadCommitSHA, headBranch.Branch.Name) } headBranchRef, err := git.GetRefPath(in.HeadBranch, gitenum.RefTypeBranch) if err != nil { return nil, nil, fmt.Errorf("failed to gerenere ref name: %w", err) } baseCommitSHA := in.BaseCommitSHA if baseCommitSHA.IsEmpty() { baseBranch, err := c.git.GetBranch(ctx, &git.GetBranchParams{ ReadParams: readParams, BranchName: in.BaseBranch, }) if err != nil { return nil, nil, fmt.Errorf("failed to get base branch: %w", err) } baseCommitSHA = baseBranch.Branch.SHA } writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return nil, nil, fmt.Errorf("failed to create RPC write params: %w", err) } var refs []git.RefUpdate if !in.DryRun { refs = append(refs, git.RefUpdate{ Name: headBranchRef, Old: headBranch.Branch.SHA, New: sha.SHA{}, // update to the result of the merge }) } mergeBase, err := c.git.MergeBase(ctx, git.MergeBaseParams{ ReadParams: readParams, Ref1: baseCommitSHA.String(), Ref2: headBranch.Branch.SHA.String(), }) if err != nil { return nil, nil, fmt.Errorf("failed to find merge base: %w", err) } const commitBulletLimit = 50 commits, err := c.git.ListCommits(ctx, &git.ListCommitsParams{ ReadParams: readParams, GitREF: in.HeadCommitSHA.String(), After: mergeBase.MergeBaseSHA.String(), Limit: commitBulletLimit, }) if err != nil { return nil, nil, fmt.Errorf("failed to read list of commits: %w", err) } commitCount := len(commits.Commits) if commitCount == 0 { return nil, nil, usererror.BadRequest("Failed to find commits between head and base") } commit0Subject, commit0Body := parser.SplitMessage(commits.Commits[0].Message) if in.Title == "" { in.Title = commit0Subject if commitCount > 1 { in.Title = fmt.Sprintf("Squashed %d commits", commits.TotalCommits) } } if in.Message == "" { in.Message = commit0Body if commitCount > 1 { sb := strings.Builder{} for i := range min(commitBulletLimit, len(commits.Commits)) { sb.WriteString("* ") sb.WriteString(commits.Commits[i].Title) sb.WriteByte('\n') } if otherCommitCount := commits.TotalCommits - len(commits.Commits); otherCommitCount > 0 { sb.WriteString(fmt.Sprintf("* and %d more commits\n", otherCommitCount)) } in.Message = sb.String() } } author := controller.IdentityFromPrincipalInfo(*session.Principal.ToPrincipalInfo()) committer := controller.SystemServicePrincipalInfo() now := time.Now() mergeOutput, err := c.git.Merge(ctx, &git.MergeParams{ WriteParams: writeParams, BaseSHA: mergeBase.MergeBaseSHA, HeadBranch: in.HeadBranch, Message: git.CommitMessage(in.Title, in.Message), Refs: refs, Committer: committer, CommitterDate: &now, Author: author, AuthorDate: &now, HeadBranchExpectedSHA: in.HeadCommitSHA, Method: gitenum.MergeMethodSquash, }) if err != nil { return nil, nil, fmt.Errorf("squash execution failed: %w", err) } if in.DryRun { // DryRun is true: Just return rule violations and list of conflicted files. // No reference is updated, so don't return the resulting commit SHA. return &types.SquashResponse{ RuleViolations: violations, DryRun: true, ConflictFiles: mergeOutput.ConflictFiles, }, nil, nil } if mergeOutput.MergeSHA.IsEmpty() || len(mergeOutput.ConflictFiles) > 0 { return nil, &types.MergeViolations{ ConflictFiles: mergeOutput.ConflictFiles, RuleViolations: violations, Message: fmt.Sprintf("Squash blocked by conflicting files: %v", mergeOutput.ConflictFiles), }, nil } return &types.SquashResponse{ NewHeadBranchSHA: mergeOutput.MergeSHA, RuleViolations: violations, }, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/linked_create.go
app/api/controller/repo/linked_create.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 repo import ( "context" "fmt" "time" "github.com/harness/gitness/app/api/controller/limiter" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/bootstrap" "github.com/harness/gitness/app/githook" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/importer" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/audit" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type LinkedCreateInput struct { ParentRef string `json:"parent_ref"` Identifier string `json:"identifier"` Description string `json:"description"` IsPublic bool `json:"is_public"` Connector importer.ConnectorDef `json:"connector"` } func (in *LinkedCreateInput) sanitize() error { if err := ValidateParentRef(in.ParentRef); err != nil { return err } return nil } func (c *Controller) LinkedCreate( ctx context.Context, session *auth.Session, in *LinkedCreateInput, ) (*RepositoryOutput, error) { if err := in.sanitize(); err != nil { return nil, err } if err := c.identifierCheck(in.Identifier, session); err != nil { return nil, err } parentSpace, err := c.getSpaceCheckAuthRepoCreation(ctx, session, in.ParentRef) if err != nil { return nil, err } isPublicAccessSupported, err := c.publicAccess. IsPublicAccessSupported(ctx, enum.PublicResourceTypeRepo, parentSpace.Path) if err != nil { return nil, fmt.Errorf( "failed to check if public access is supported for parent space %q: %w", parentSpace.Path, err, ) } if in.IsPublic && !isPublicAccessSupported { return nil, errPublicRepoCreationDisabled } defaultBranch, err := c.verifyConnectorAccess(ctx, in.Connector) if err != nil { return nil, errors.InvalidArgument("Failed to use connector to access the remote repository.") } repo := importer.NewRepo( parentSpace.ID, parentSpace.Path, in.Identifier, in.Description, &session.Principal, defaultBranch, ) repo.Type = enum.RepoTypeLinked now := time.Now().UnixMilli() err = c.tx.WithTx(ctx, func(ctx context.Context) error { if err := c.resourceLimiter.RepoCount(ctx, parentSpace.ID, 1); err != nil { return fmt.Errorf("resource limit exceeded: %w", limiter.ErrMaxNumReposReached) } // lock the space for update during repo creation to prevent racing conditions with space soft delete. _, err = c.spaceStore.FindForUpdate(ctx, parentSpace.ID) if err != nil { return fmt.Errorf("failed to find the parent space: %w", err) } err = c.repoStore.Create(ctx, repo) if err != nil { return fmt.Errorf("failed to create repository: %w", err) } err = c.linkedRepoStore.Create(ctx, &types.LinkedRepo{ RepoID: repo.ID, Version: 0, Created: now, Updated: now, LastFullSync: now, ConnectorPath: in.Connector.Path, ConnectorIdentifier: in.Connector.Identifier, }) if err != nil { return fmt.Errorf("failed to create linked repository: %w", err) } err = c.importLinked.Run(ctx, repo.ID, in.IsPublic) if err != nil { return fmt.Errorf("failed to start link repository job: %w", err) } return nil }) if err != nil { return nil, err } repo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repo.Path) repo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path) err = c.auditService.Log(ctx, session.Principal, audit.NewResource(audit.ResourceTypeRepository, repo.Identifier), audit.ActionCreated, paths.Parent(repo.Path), audit.WithNewObject(audit.RepositoryObject{ Repository: *repo, IsPublic: false, }), ) if err != nil { log.Warn().Msgf("failed to insert audit log for import repository operation: %s", err) } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeRepositoryCreate, Principal: session.Principal.ToPrincipalInfo(), Path: repo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, instrument.PropertyRepositoryCreationType: instrument.CreationTypeLink, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for import repository operation: %s", err) } repoOutput, err := GetRepoOutputWithAccess(ctx, c.repoFinder, false, repo) if err != nil { return nil, fmt.Errorf("failed to get repo output: %w", err) } return repoOutput, nil } func (c *Controller) verifyConnectorAccess(ctx context.Context, connector importer.ConnectorDef) (string, error) { systemPrincipal := bootstrap.NewSystemServiceSession().Principal gitIdentity := identityFromPrincipal(systemPrincipal) accessInfo, err := c.connectorService.GetAccessInfo(ctx, connector) if err != nil { return "", fmt.Errorf("failed to get repository access info from connector: %w", err) } urlWithCredentials, err := accessInfo.URLWithCredentials() if err != nil { return "", fmt.Errorf("failed to get repository URL: %w", err) } envVars, err := githook.GenerateEnvironmentVariables( ctx, c.urlProvider.GetInternalAPIURL(ctx), 0, systemPrincipal.ID, true, true, ) if err != nil { return "", fmt.Errorf("failed to generate git hook environment variables: %w", err) } now := time.Now() resp, err := c.git.CreateRepository(ctx, &git.CreateRepositoryParams{ Actor: *gitIdentity, EnvVars: envVars, DefaultBranch: "main", Files: nil, Author: gitIdentity, AuthorDate: &now, Committer: gitIdentity, CommitterDate: &now, }) if err != nil { return "", fmt.Errorf("failed to create repository: %w", err) } gitUID := resp.UID writeParams := git.WriteParams{ Actor: *gitIdentity, RepoUID: gitUID, EnvVars: envVars, } defer func() { if errDel := c.git.DeleteRepository(context.WithoutCancel(ctx), &git.DeleteRepositoryParams{ WriteParams: writeParams, }); errDel != nil { log.Warn().Err(errDel). Msg("failed to delete temporary git repository") } }() respDefBranch, err := c.git.GetRemoteDefaultBranch(ctx, &git.GetRemoteDefaultBranchParams{ ReadParams: git.ReadParams{RepoUID: gitUID}, Source: urlWithCredentials, }) if err != nil { return "", fmt.Errorf("failed to get repository default branch: %w", err) } return respDefBranch.BranchName, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/wire.go
app/api/controller/repo/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 repo import ( "github.com/harness/gitness/app/api/controller/lfs" "github.com/harness/gitness/app/api/controller/limiter" "github.com/harness/gitness/app/auth/authz" repoevents "github.com/harness/gitness/app/events/repo" "github.com/harness/gitness/app/services/codeowners" "github.com/harness/gitness/app/services/importer" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/keywordsearch" "github.com/harness/gitness/app/services/label" "github.com/harness/gitness/app/services/locker" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/services/publickey" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/services/rules" "github.com/harness/gitness/app/services/settings" "github.com/harness/gitness/app/services/usergroup" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/audit" "github.com/harness/gitness/git" "github.com/harness/gitness/lock" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideController, ) func ProvideController( config *types.Config, tx dbtx.Transactor, urlProvider url.Provider, authorizer authz.Authorizer, repoStore store.RepoStore, linkedRepoStore store.LinkedRepoStore, spaceStore store.SpaceStore, pipelineStore store.PipelineStore, principalStore store.PrincipalStore, executionStore store.ExecutionStore, ruleStore store.RuleStore, checkStore store.CheckStore, pullReqStore store.PullReqStore, settings *settings.Service, principalInfoCache store.PrincipalInfoCache, protectionManager *protection.Manager, rpcClient git.Interface, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder, importer *importer.JobRepository, referenceSync *importer.JobReferenceSync, importLinked *importer.JobRepositoryLink, codeOwners *codeowners.Service, repoReporter *repoevents.Reporter, indexer keywordsearch.Indexer, limiter limiter.ResourceLimiter, locker *locker.Locker, auditService audit.Service, mtxManager lock.MutexManager, identifierCheck check.RepoIdentifier, repoChecks Check, publicAccess publicaccess.Service, labelSvc *label.Service, instrumentation instrument.Service, userGroupStore store.UserGroupStore, userGroupService usergroup.Service, rulesSvc *rules.Service, sseStreamer sse.Streamer, lfsCtrl *lfs.Controller, favoriteStore store.FavoriteStore, signatureVerifyService publickey.SignatureVerifyService, connectorService importer.ConnectorService, ) *Controller { return NewController(config, tx, urlProvider, authorizer, repoStore, linkedRepoStore, spaceStore, pipelineStore, executionStore, principalStore, ruleStore, checkStore, pullReqStore, settings, principalInfoCache, protectionManager, rpcClient, spaceFinder, repoFinder, importer, referenceSync, importLinked, codeOwners, repoReporter, indexer, limiter, locker, auditService, mtxManager, identifierCheck, repoChecks, publicAccess, labelSvc, instrumentation, userGroupStore, userGroupService, rulesSvc, sseStreamer, lfsCtrl, favoriteStore, signatureVerifyService, connectorService, ) } func ProvideRepoCheck() Check { return NewNoOpRepoChecks() }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/label_value_delete.go
app/api/controller/repo/label_value_delete.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 repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) // DeleteLabelValue deletes a label value for the specified repository. func (c *Controller) DeleteLabelValue( ctx context.Context, session *auth.Session, repoRef string, key string, value string, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return fmt.Errorf("failed to acquire access to repo: %w", err) } if err := c.labelSvc.DeleteValue(ctx, nil, &repo.ID, key, value); err != nil { return fmt.Errorf("failed to delete repo label value: %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/app/api/controller/repo/commit.go
app/api/controller/repo/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 repo import ( "cmp" "context" "encoding/base64" "fmt" "strings" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/bootstrap" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/audit" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // CommitFileAction holds file operation data. type CommitFileAction struct { Action git.FileAction `json:"action"` Path string `json:"path"` Payload string `json:"payload"` Encoding enum.ContentEncodingType `json:"encoding"` // SHA can be used for optimistic locking of an update action (Optional). // The provided value is compared against the latest sha of the file that's being updated. // If the SHA doesn't match, the update fails. // WARNING: If no SHA is provided, the update action will blindly overwrite the file's content. SHA sha.SHA `json:"sha"` } // CommitFilesOptions holds the data for file operations. type CommitFilesOptions struct { Title string `json:"title"` Message string `json:"message"` Branch string `json:"branch"` NewBranch string `json:"new_branch"` Actions []CommitFileAction `json:"actions"` Author *git.Identity `json:"author"` DryRunRules bool `json:"dry_run_rules"` BypassRules bool `json:"bypass_rules"` } func (in *CommitFilesOptions) Sanitize() error { in.Title = strings.TrimSpace(in.Title) in.Message = strings.TrimSpace(in.Message) in.Branch = strings.TrimSpace(in.Branch) in.NewBranch = strings.TrimSpace(in.NewBranch) if in.Author != nil { in.Author.Name = strings.TrimSpace(in.Author.Name) in.Author.Email = strings.TrimSpace(in.Author.Email) } if len(in.Title) > 1024 { // TODO: Check if the title length limit is acceptable. return usererror.BadRequest("Commit title is too long.") } if len(in.Message) > 65536 { // TODO: Check if the message length limit is acceptable. return usererror.BadRequest("Commit message is too long.") } return nil } func mapChangedFiles(files []git.FileReference) []types.FileReference { changedFiles := make([]types.FileReference, len(files)) for i, file := range files { changedFiles[i] = types.FileReference{ Path: file.Path, SHA: file.SHA, } } return changedFiles } func (c *Controller) CommitFiles(ctx context.Context, session *auth.Session, repoRef string, in *CommitFilesOptions, ) (types.CommitFilesResponse, []types.RuleViolations, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return types.CommitFilesResponse{}, nil, err } if err := in.Sanitize(); err != nil { return types.CommitFilesResponse{}, nil, err } rules, isRepoOwner, err := c.fetchBranchRules(ctx, session, repo) if err != nil { return types.CommitFilesResponse{}, nil, err } var refAction protection.RefAction var branchName string if in.NewBranch != "" { refAction = protection.RefActionCreate branchName = in.NewBranch } else { refAction = protection.RefActionUpdate branchName = in.Branch } violations, err := rules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: in.BypassRules, IsRepoOwner: isRepoOwner, Repo: repo, RefAction: refAction, RefType: protection.RefTypeBranch, RefNames: []string{branchName}, }) if err != nil { return types.CommitFilesResponse{}, nil, fmt.Errorf("failed to verify protection rules: %w", err) } if in.DryRunRules { return types.CommitFilesResponse{ DryRunRulesOutput: types.DryRunRulesOutput{ DryRunRules: true, RuleViolations: violations, }, }, nil, nil } if protection.IsCritical(violations) { return types.CommitFilesResponse{}, violations, nil } actions := make([]git.CommitFileAction, len(in.Actions)) for i, action := range in.Actions { var rawPayload []byte switch action.Encoding { case enum.ContentEncodingTypeBase64: rawPayload, err = base64.StdEncoding.DecodeString(action.Payload) if err != nil { return types.CommitFilesResponse{}, nil, errors.Internal(err, "failed to decode base64 payload") } case enum.ContentEncodingTypeUTF8: fallthrough default: // by default we treat content as is rawPayload = []byte(action.Payload) } actions[i] = git.CommitFileAction{ Action: action.Action, Path: action.Path, Payload: rawPayload, SHA: action.SHA, } } // Create internal write params. Note: This will skip the pre-commit protection rules check. writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return types.CommitFilesResponse{}, nil, fmt.Errorf("failed to create RPC write params: %w", err) } now := time.Now() commit, err := c.git.CommitFiles(ctx, &git.CommitFilesParams{ WriteParams: writeParams, Message: git.CommitMessage(in.Title, in.Message), Branch: in.Branch, NewBranch: in.NewBranch, Actions: actions, Committer: identityFromPrincipal(bootstrap.NewSystemServiceSession().Principal), CommitterDate: &now, Author: cmp.Or(in.Author, identityFromPrincipal(session.Principal)), AuthorDate: &now, }) if err != nil { return types.CommitFilesResponse{}, nil, err } if protection.IsBypassed(violations) { err = c.auditService.Log(ctx, session.Principal, audit.NewResource( audit.ResourceTypeRepository, repo.Identifier, audit.RepoPath, repo.Path, audit.BypassAction, audit.BypassActionCommitted, audit.BypassedResourceType, audit.BypassedResourceTypeCommit, audit.BypassedResourceName, commit.CommitID.String(), audit.ResourceName, fmt.Sprintf( audit.BypassSHALabelFormat, repo.Identifier, commit.CommitID.String()[0:6], ), ), audit.ActionBypassed, paths.Parent(repo.Path), audit.WithNewObject(audit.CommitObject{ CommitSHA: commit.CommitID.String(), RepoPath: repo.Path, RuleViolations: violations, }), ) } if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for commit operation: %s", err) } return types.CommitFilesResponse{ CommitID: commit.CommitID, DryRunRulesOutput: types.DryRunRulesOutput{ RuleViolations: violations, }, ChangedFiles: mapChangedFiles(commit.ChangedFiles), }, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/create.go
app/api/controller/repo/create.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 repo import ( "bytes" "context" "database/sql" "encoding/json" "fmt" "strings" "time" "github.com/harness/gitness/app/api/controller/limiter" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/bootstrap" repoevents "github.com/harness/gitness/app/events/repo" "github.com/harness/gitness/app/githook" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/audit" "github.com/harness/gitness/git" "github.com/harness/gitness/resources" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) var ( // errRepositoryRequiresParent if the user tries to create a repo without a parent space. errRepositoryRequiresParent = usererror.BadRequest( "Parent space required - standalone repositories are not supported.") ) type CreateInput struct { ParentRef string `json:"parent_ref"` // TODO [CODE-1363]: remove after identifier migration. UID string `json:"uid" deprecated:"true"` Identifier string `json:"identifier"` DefaultBranch string `json:"default_branch"` Description string `json:"description"` IsPublic bool `json:"is_public"` ForkID int64 `json:"fork_id"` Tags types.RepoTags `json:"tags"` CreateFileOptions } type CreateFileOptions struct { Readme bool `json:"readme"` License string `json:"license"` GitIgnore string `json:"git_ignore"` } // Create creates a new repository. // //nolint:gocognit func (c *Controller) Create(ctx context.Context, session *auth.Session, in *CreateInput) (*RepositoryOutput, error) { if err := c.sanitizeCreateInput(in, session); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } parentSpace, err := c.getSpaceCheckAuthRepoCreation(ctx, session, in.ParentRef) if err != nil { return nil, err } isPublicAccessSupported, err := c.publicAccess. IsPublicAccessSupported(ctx, enum.PublicResourceTypeRepo, parentSpace.Path) if err != nil { return nil, fmt.Errorf( "failed to check if public access is supported for parent space %q: %w", parentSpace.Path, err, ) } if in.IsPublic && !isPublicAccessSupported { return nil, errPublicRepoCreationDisabled } err = c.repoCheck.Create(ctx, session, &CheckInput{ ParentRef: parentSpace.Path, Identifier: in.Identifier, DefaultBranch: in.DefaultBranch, Description: in.Description, IsPublic: in.IsPublic, IsFork: false, CreateFileOptions: in.CreateFileOptions, }) if err != nil { return nil, err } gitResp, isEmpty, err := c.createGitRepository( ctx, session, in.Identifier, in.Description, in.DefaultBranch, in.CreateFileOptions) if err != nil { return nil, fmt.Errorf("error creating repository on git: %w", err) } var repo *types.Repository err = c.tx.WithTx(ctx, func(ctx context.Context) error { if err := c.resourceLimiter.RepoCount(ctx, parentSpace.ID, 1); err != nil { return fmt.Errorf("resource limit exceeded: %w", limiter.ErrMaxNumReposReached) } // lock the space for update during repo creation to prevent racing conditions with space soft delete. _, err = c.spaceStore.FindForUpdate(ctx, parentSpace.ID) if err != nil { return fmt.Errorf("failed to find the parent space: %w", err) } now := time.Now().UnixMilli() tags, _ := json.Marshal(in.Tags) // should never fail as we sanitize the input type repo = &types.Repository{ Version: 0, ParentID: parentSpace.ID, Identifier: in.Identifier, GitUID: gitResp.UID, Description: in.Description, CreatedBy: session.Principal.ID, Created: now, Updated: now, LastGITPush: now, // even in case of an empty repo, the git repo got created. ForkID: in.ForkID, DefaultBranch: in.DefaultBranch, IsEmpty: isEmpty, Tags: tags, } return c.repoStore.Create(ctx, repo) }, sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { // best effort cleanup if dErr := c.DeleteGitRepository(ctx, session, gitResp.UID); dErr != nil { log.Ctx(ctx).Warn().Err(dErr).Msg("failed to delete repo for cleanup") } return nil, err } err = c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repo.Path, in.IsPublic) if err != nil { if dErr := c.publicAccess.Delete(ctx, enum.PublicResourceTypeRepo, repo.Path); dErr != nil { return nil, fmt.Errorf("failed to set repo public access (and public access cleanup: %w): %w", dErr, err) } // only cleanup repo itself if cleanup of public access succeeded (to avoid leaking public access) if dErr := c.PurgeNoAuth(ctx, session, repo); dErr != nil { return nil, fmt.Errorf("failed to set repo public access (and repo purge: %w): %w", dErr, err) } return nil, fmt.Errorf("failed to set repo public access (successful cleanup): %w", err) } // backfil GitURL repo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repo.Path) repo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path) repoOutput, err := GetRepoOutputWithAccess(ctx, c.repoFinder, in.IsPublic, repo) if err != nil { return nil, fmt.Errorf("failed to get repo output: %w", err) } err = c.auditService.Log(ctx, session.Principal, audit.NewResource(audit.ResourceTypeRepository, repo.Identifier), audit.ActionCreated, paths.Parent(repo.Path), audit.WithNewObject(audit.RepositoryObject{ Repository: repoOutput.Repository, IsPublic: repoOutput.IsPublic, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for create repository operation: %s", err) } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeRepositoryCreate, Principal: session.Principal.ToPrincipalInfo(), Path: repo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, instrument.PropertyRepositoryCreationType: instrument.CreationTypeCreate, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for create repository operation: %s", err) } c.eventReporter.Created(ctx, &repoevents.CreatedPayload{ Base: eventBase(repo.Core(), &session.Principal), IsPublic: in.IsPublic, }) // index repository if files are created if !repo.IsEmpty { err = c.indexer.Index(ctx, repo) if err != nil { log.Ctx(ctx).Warn().Err(err).Int64("repo_id", repo.ID).Msg("failed to index repo") } } return repoOutput, nil } func (c *Controller) sanitizeCreateInput(in *CreateInput, session *auth.Session) error { // TODO [CODE-1363]: remove after identifier migration. if in.Identifier == "" { in.Identifier = in.UID } if err := ValidateParentRef(in.ParentRef); err != nil { return err } if err := c.identifierCheck(in.Identifier, session); err != nil { return err } in.Description = strings.TrimSpace(in.Description) if err := check.Description(in.Description); err != nil { return err } if in.DefaultBranch == "" { in.DefaultBranch = c.defaultBranch } err := in.Tags.Sanitize() if err != nil { return fmt.Errorf("failed to sanitize tags: %w", err) } return nil } func (c *Controller) createGitRepository( ctx context.Context, session *auth.Session, identifier string, description string, defaultBranch string, options CreateFileOptions, ) (*git.CreateRepositoryOutput, bool, error) { var ( err error content []byte ) files := make([]git.File, 0, 3) // readme, gitignore, licence if options.Readme { content = createReadme(identifier, description) files = append(files, git.File{ Path: "README.md", Content: content, }) } if options.License != "" && options.License != "none" { content, err = resources.ReadLicense(options.License) if err != nil { return nil, false, fmt.Errorf("failed to read license '%s': %w", options.License, err) } files = append(files, git.File{ Path: "LICENSE", Content: content, }) } if options.GitIgnore != "" { content, err = resources.ReadGitIgnore(options.GitIgnore) if err != nil { return nil, false, fmt.Errorf("failed to read git ignore '%s': %w", options.GitIgnore, err) } files = append(files, git.File{ Path: ".gitignore", Content: content, }) } // generate envars (add everything githook CLI needs for execution) envVars, err := githook.GenerateEnvironmentVariables( ctx, c.urlProvider.GetInternalAPIURL(ctx), 0, session.Principal.ID, true, true, ) if err != nil { return nil, false, fmt.Errorf("failed to generate git hook environment variables: %w", err) } actor := identityFromPrincipal(session.Principal) committer := identityFromPrincipal(bootstrap.NewSystemServiceSession().Principal) now := time.Now() resp, err := c.git.CreateRepository(ctx, &git.CreateRepositoryParams{ Actor: *actor, EnvVars: envVars, DefaultBranch: defaultBranch, Files: files, Author: actor, AuthorDate: &now, Committer: committer, CommitterDate: &now, }) if err != nil { return nil, false, fmt.Errorf("failed to create repo on: %w", err) } return resp, len(files) == 0, nil } func createReadme(name, description string) []byte { content := bytes.Buffer{} content.WriteString("# " + name + "\n") if description != "" { content.WriteString(description) } return content.Bytes() } func identityFromPrincipal(p types.Principal) *git.Identity { return &git.Identity{ Name: p.DisplayName, Email: p.Email, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/label_update.go
app/api/controller/repo/label_update.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 repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // UpdateLabel updates a label for the specified repository. func (c *Controller) UpdateLabel( ctx context.Context, session *auth.Session, repoRef string, key string, in *types.UpdateLabelInput, ) (*types.Label, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } if err := in.Sanitize(); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } label, err := c.labelSvc.Update(ctx, session.Principal.ID, nil, &repo.ID, key, in) if err != nil { return nil, fmt.Errorf("failed to update repo label: %w", err) } return label, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/pipeline_generate.go
app/api/controller/repo/pipeline_generate.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 repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types/enum" ) // PipelineGenerate returns automatically generate pipeline YAML for a repository. func (c *Controller) PipelineGenerate( ctx context.Context, session *auth.Session, repoRef string, ) ([]byte, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return nil, err } result, err := c.git.GeneratePipeline(ctx, &git.GeneratePipelineParams{ ReadParams: git.CreateReadParams(repo), }) if err != nil { return nil, fmt.Errorf("failed to generate pipeline: %w", err) } return result.PipelineYAML, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/list_pipelines.go
app/api/controller/repo/list_pipelines.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 repo import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListPipelines lists the pipelines under a repository. func (c *Controller) ListPipelines( ctx context.Context, session *auth.Session, repoRef string, filter *types.ListPipelinesFilter, ) ([]*types.Pipeline, int64, error) { repo, err := GetRepo(ctx, c.repoFinder, repoRef) if err != nil { return nil, 0, fmt.Errorf("failed to find repo: %w", err) } if err := apiauth.CheckRepoState(ctx, session, repo, enum.PermissionPipelineView); err != nil { return nil, 0, err } if err := apiauth.CheckPipeline(ctx, c.authorizer, session, repo.Path, "", enum.PermissionPipelineView); err != nil { return nil, 0, fmt.Errorf("access check failed: %w", err) } var count int64 var pipelines []*types.Pipeline err = c.tx.WithTx(ctx, func(ctx context.Context) (err error) { count, err = c.pipelineStore.Count(ctx, repo.ID, filter) if err != nil { return fmt.Errorf("failed to count child executions: %w", err) } if !filter.Latest { pipelines, err = c.pipelineStore.List(ctx, repo.ID, filter) if err != nil { return fmt.Errorf("failed to list pipelines: %w", err) } } else { pipelines, err = c.pipelineStore.ListLatest(ctx, repo.ID, filter) if err != nil { return fmt.Errorf("failed to list latest pipelines: %w", err) } } pipelineIDs := make([]int64, len(pipelines)) for i, pipeline := range pipelines { pipelineIDs[i] = pipeline.ID } execs, err := c.executionStore.ListByPipelineIDs(ctx, pipelineIDs, filter.LastExecutions) if err != nil { return fmt.Errorf("failed to list executions by pipeline IDs: %w", err) } for _, pipeline := range pipelines { pipeline.LastExecutions = execs[pipeline.ID] } return nil }, dbtx.TxDefaultReadOnly) if err != nil { return pipelines, count, fmt.Errorf("failed to list pipelines: %w", err) } return pipelines, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/helper.go
app/api/controller/repo/helper.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 repo import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/store" "github.com/harness/gitness/errors" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "golang.org/x/exp/slices" ) var importingStates = []enum.RepoState{ enum.RepoStateGitImport, enum.RepoStateMigrateDataImport, enum.RepoStateMigrateGitPush, } // GetRepo fetches a repository. func GetRepo( ctx context.Context, repoFinder refcache.RepoFinder, repoRef string, ) (*types.RepositoryCore, error) { if repoRef == "" { return nil, usererror.BadRequest("A valid repository reference must be provided.") } repo, err := repoFinder.FindByRef(ctx, repoRef) if err != nil { return nil, fmt.Errorf("failed to find repository: %w", err) } return repo, nil } // GetRepoCheckAccess fetches a repo with option to enforce repo state check // and checks if the current user has permission to access it. func GetRepoCheckAccess( ctx context.Context, repoFinder refcache.RepoFinder, authorizer authz.Authorizer, session *auth.Session, repoRef string, reqPermission enum.Permission, allowLinked bool, allowedRepoStates ...enum.RepoState, ) (*types.RepositoryCore, error) { repo, err := GetRepo(ctx, repoFinder, repoRef) if err != nil { return nil, fmt.Errorf("failed to find repo: %w", err) } if !allowLinked && repo.Type == enum.RepoTypeLinked && reqPermission != enum.PermissionRepoView { return nil, errors.Forbidden("Changes are not allowed to a linked repository.") } if err := apiauth.CheckRepoState(ctx, session, repo, reqPermission, allowedRepoStates...); err != nil { return nil, err } if err = apiauth.CheckRepo(ctx, authorizer, session, repo, reqPermission); err != nil { return nil, fmt.Errorf("access check failed: %w", err) } return repo, nil } func GetSpaceCheckAuthRepoCreation( ctx context.Context, spaceFinder refcache.SpaceFinder, authorizer authz.Authorizer, session *auth.Session, parentRef string, ) (*types.SpaceCore, error) { space, err := spaceFinder.FindByRef(ctx, parentRef) if err != nil { return nil, fmt.Errorf("parent space not found: %w", err) } // create is a special case - check permission without specific resource err = apiauth.CheckSpaceScope( ctx, authorizer, session, space, enum.ResourceTypeRepo, enum.PermissionRepoCreate, ) if err != nil { return nil, fmt.Errorf("auth check failed: %w", err) } return space, nil } func GetRepoOutput( ctx context.Context, publicAccess publicaccess.Service, repoFinder refcache.RepoFinder, repo *types.Repository, ) (*RepositoryOutput, error) { isPublic, err := publicAccess.Get(ctx, enum.PublicResourceTypeRepo, repo.Path) if err != nil { return nil, fmt.Errorf("failed to check if repo is public: %w", err) } var upstreamRepo *types.RepositoryCore if repo.ForkID != 0 { upstreamRepo, err = repoFinder.FindByID(ctx, repo.ForkID) if err != nil { return nil, fmt.Errorf("failed to find repo fork %d: %w", repo.ForkID, err) } } return &RepositoryOutput{ Repository: *repo, IsPublic: isPublic, Importing: slices.Contains(importingStates, repo.State), Archived: repo.State == enum.RepoStateArchived, Upstream: upstreamRepo, }, nil } func GetRepoOutputWithAccess( ctx context.Context, repoFinder refcache.RepoFinder, isPublic bool, repo *types.Repository, ) (*RepositoryOutput, error) { var upstreamRepo *types.RepositoryCore if repo.ForkID != 0 { var err error upstreamRepo, err = repoFinder.FindByID(ctx, repo.ForkID) if err != nil { return nil, fmt.Errorf("failed to find repo fork %d: %w", repo.ForkID, err) } } return &RepositoryOutput{ Repository: *repo, IsPublic: isPublic, Importing: slices.Contains(importingStates, repo.State), Archived: repo.State == enum.RepoStateArchived, Upstream: upstreamRepo, }, nil } // GetRepoCheckServiceAccountAccess fetches a repo with option to enforce repo state check // and checks if the current user has permission to access service accounts within repo. func GetRepoCheckServiceAccountAccess( ctx context.Context, session *auth.Session, authorizer authz.Authorizer, repoRef string, reqPermission enum.Permission, repoFinder refcache.RepoFinder, repoStore store.RepoStore, spaceStore store.SpaceStore, allowedRepoStates ...enum.RepoState, ) (*types.RepositoryCore, error) { repo, err := GetRepo(ctx, repoFinder, repoRef) if err != nil { return nil, fmt.Errorf("failed to find repo: %w", err) } if err := apiauth.CheckRepoState(ctx, session, repo, reqPermission, allowedRepoStates...); err != nil { return nil, err } if err := apiauth.CheckServiceAccount(ctx, authorizer, session, spaceStore, repoStore, enum.ParentResourceTypeRepo, repo.ID, "", reqPermission, ); err != nil { return nil, fmt.Errorf("access check failed: %w", err) } return repo, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/archive.go
app/api/controller/repo/archive.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 repo import ( "context" "io" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/git/api" "github.com/harness/gitness/types/enum" ) func (c *Controller) Archive( ctx context.Context, session *auth.Session, repoRef string, params api.ArchiveParams, w io.Writer, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return err } return c.git.Archive(ctx, git.ArchiveParams{ ReadParams: git.CreateReadParams(repo), ArchiveParams: params, }, w) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/rule_find.go
app/api/controller/repo/rule_find.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 repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // RuleFind returns the protection rule by identifier. func (c *Controller) RuleFind(ctx context.Context, session *auth.Session, repoRef string, identifier string, ) (*types.Rule, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } rule, err := c.rulesSvc.Find(ctx, enum.RuleParentRepo, repo.ID, identifier) if err != nil { return nil, fmt.Errorf("failed to find repo-level protection rule by identifier: %w", err) } return rule, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/label_value_update.go
app/api/controller/repo/label_value_update.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 repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // UpdateLabelValue updates a label value for the specified label and repository. func (c *Controller) UpdateLabelValue( ctx context.Context, session *auth.Session, repoRef string, key string, value string, in *types.UpdateValueInput, ) (*types.LabelValue, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } if err := in.Sanitize(); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } label, err := c.labelSvc.Find(ctx, nil, &repo.ID, key) if err != nil { return nil, fmt.Errorf("failed to find repo label: %w", err) } labelValue, err := c.labelSvc.UpdateValue( ctx, session.Principal.ID, label.ID, value, in) if err != nil { return nil, fmt.Errorf("failed to update repo label value: %w", err) } return labelValue, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/restore.go
app/api/controller/repo/restore.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 repo import ( "context" "database/sql" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/controller/limiter" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/errors" "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type RestoreInput struct { NewIdentifier *string `json:"new_identifier,omitempty"` NewParentRef *string `json:"new_parent_ref,omitempty"` } func (c *Controller) Restore( ctx context.Context, session *auth.Session, repoRef string, deletedAt int64, in *RestoreInput, ) (*RepositoryOutput, error) { repo, err := c.repoFinder.FindDeletedByRef(ctx, repoRef, deletedAt) if err != nil { return nil, fmt.Errorf("failed to find repository: %w", err) } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo.Core(), enum.PermissionRepoCreate); err != nil { return nil, fmt.Errorf("access check failed: %w", err) } if err = c.repoCheck.LifecycleRestriction(ctx, session, repo.Core()); err != nil { return nil, err } if repo.Deleted == nil { return nil, usererror.BadRequest("Cannot restore a repo that hasn't been deleted") } parentID := repo.ParentID if in.NewParentRef != nil { space, err := c.spaceStore.FindByRef(ctx, *in.NewParentRef) if errors.Is(err, store.ErrResourceNotFound) { return nil, usererror.BadRequest("The provided new parent ref wasn't found.") } if err != nil { return nil, fmt.Errorf("failed to find the parent ref '%s': %w", *in.NewParentRef, err) } parentID = space.ID } return c.RestoreNoAuth(ctx, repo, in.NewIdentifier, parentID) } func (c *Controller) RestoreNoAuth( ctx context.Context, repo *types.Repository, newIdentifier *string, newParentID int64, ) (*RepositoryOutput, error) { var err error err = c.tx.WithTx(ctx, func(ctx context.Context) error { if err := c.resourceLimiter.RepoCount(ctx, newParentID, 1); err != nil { return fmt.Errorf("resource limit exceeded: %w", limiter.ErrMaxNumReposReached) } repo, err = c.repoStore.Restore(ctx, repo, newIdentifier, &newParentID) if err != nil { return fmt.Errorf("failed to restore the repo: %w", err) } return nil }, sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { return nil, fmt.Errorf("failed to restore the repo: %w", err) } // Repos restored as private since public access data has been deleted upon deletion. repoOutput, err := GetRepoOutputWithAccess(ctx, c.repoFinder, false, repo) if err != nil { return nil, fmt.Errorf("failed to get repo output: %w", err) } return repoOutput, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/move.go
app/api/controller/repo/move.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 repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // MoveInput is used for moving a repo. type MoveInput struct { // TODO [CODE-1363]: remove after identifier migration. UID *string `json:"uid" deprecated:"true"` Identifier *string `json:"identifier"` // ParentRef can be either a space ID or space path ParentRef *string `json:"parent_ref"` } func (i *MoveInput) hasChanges( repo *types.Repository, parentSpace *types.SpaceCore, targetParentSpace *types.SpaceCore, ) bool { if i.Identifier != nil && *i.Identifier != repo.Identifier { return true } if i.ParentRef != nil && targetParentSpace.ID != parentSpace.ID { return true } return false } // Move moves a repository to a new identifier and/or parent space. // //nolint:gocognit // refactor if needed func (c *Controller) Move(ctx context.Context, session *auth.Session, repoRef string, in *MoveInput, ) (*RepositoryOutput, error) { if err := c.sanitizeMoveInput(in, session); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } repoCore, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, fmt.Errorf("failed to find or acquire access to repo: %w", err) } repo, err := c.repoStore.Find(ctx, repoCore.ID) if err != nil { return nil, fmt.Errorf("failed to find repo by ID: %w", err) } currentParentSpace, err := c.spaceFinder.FindByID(ctx, repo.ParentID) if err != nil { return nil, fmt.Errorf("failed to find current parent space: %w", err) } targetParentSpace := currentParentSpace if in.ParentRef != nil { targetParentSpace, err = c.getSpaceCheckAuthRepoCreation(ctx, session, *in.ParentRef) if err != nil { return nil, fmt.Errorf("failed to access target parent space: %w", err) } } if !in.hasChanges(repo, currentParentSpace, targetParentSpace) { return GetRepoOutput(ctx, c.publicAccess, c.repoFinder, repo) } movedRepo, err := c.MoveNoAuth(ctx, repo, in.Identifier, targetParentSpace.ID) if err != nil { return nil, fmt.Errorf("failed to move repo: %w", err) } movedRepo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, movedRepo.Path) movedRepo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, movedRepo.Path) // TODO: add audit log log.Ctx(ctx).Info().Msgf( "Moved repository %s to %s operation performed by %s", repo.Path, movedRepo.Path, session.Principal.Email) return GetRepoOutput(ctx, c.publicAccess, c.repoFinder, movedRepo) } func (c *Controller) MoveNoAuth( ctx context.Context, repo *types.Repository, newIdentifier *string, targetParentSpaceID int64, ) (*types.Repository, error) { isPublic, err := c.publicAccess.Get(ctx, enum.PublicResourceTypeRepo, repo.Path) if err != nil { return nil, fmt.Errorf("failed to get repo public access: %w", err) } // remove public access from old repo path to avoid leaking it if err := c.publicAccess.Delete( ctx, enum.PublicResourceTypeRepo, repo.Path, ); err != nil { return nil, fmt.Errorf("failed to remove public access on the original path: %w", err) } // TODO add a repo level lock here to avoid racing condition or partial repo update w/o setting repo public access movedRepo, err := c.repoStore.UpdateOptLock(ctx, repo, func(r *types.Repository) error { if newIdentifier != nil { r.Identifier = *newIdentifier } if targetParentSpaceID != r.ParentID { r.ParentID = targetParentSpaceID } return nil }) if err != nil { return nil, fmt.Errorf("failed to update repo: %w", err) } // clear old repo from cache c.repoFinder.MarkChanged(ctx, repo.Core()) // set public access for the new repo path if err := c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, movedRepo.Path, isPublic); err != nil { // ensure public access for new repo path is cleaned up first or we risk leaking it if dErr := c.publicAccess.Delete(ctx, enum.PublicResourceTypeRepo, movedRepo.Path); dErr != nil { return nil, fmt.Errorf("failed to set repo public access (and public access cleanup: %w): %w", dErr, err) } // revert identifier and parent changes first var dErr error _, dErr = c.repoStore.UpdateOptLock(ctx, movedRepo, func(r *types.Repository) error { r.Identifier = repo.Identifier r.ParentID = repo.ParentID return nil }) if dErr != nil { return nil, fmt.Errorf( "failed to set public access for new path (and reverting of move: %w): %w", dErr, err, ) } // clear updated repo from cache c.repoFinder.MarkChanged(ctx, movedRepo.Core()) // revert public access changes only after we successfully restored original path if dErr = c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repo.Path, isPublic); dErr != nil { return nil, fmt.Errorf( "failed to set public access for new path (and reverting of public access: %w): %w", dErr, err, ) } return nil, fmt.Errorf("failed to set repo public access for new path (cleanup successful): %w", err) } return movedRepo, nil } func (c *Controller) sanitizeMoveInput(in *MoveInput, session *auth.Session) error { // TODO [CODE-1363]: remove after identifier migration. if in.Identifier == nil { in.Identifier = in.UID } if in.Identifier != nil { if err := c.identifierCheck(*in.Identifier, session); err != nil { return err } } if in.ParentRef != nil { if err := ValidateParentRef(*in.ParentRef); err != nil { return fmt.Errorf("invalid space reference: %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/app/api/controller/repo/get_commit.go
app/api/controller/repo/get_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 repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // GetCommit gets a repo commit. func (c *Controller) GetCommit(ctx context.Context, session *auth.Session, repoRef string, rev string, ) (*types.Commit, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } rpcOut, err := c.git.GetCommit(ctx, &git.GetCommitParams{ ReadParams: git.CreateReadParams(repo), Revision: rev, }) if err != nil { return nil, fmt.Errorf("failed to get commit: %w", err) } commit := controller.MapCommit(&rpcOut.Commit) return commit, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/summary.go
app/api/controller/repo/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 repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // Summary returns commit, branch, tag and pull req count for a repo. func (c *Controller) Summary( ctx context.Context, session *auth.Session, repoRef string, ) (*types.RepositorySummary, error) { repoCore, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("access check failed: %w", err) } repo, err := c.repoStore.Find(ctx, repoCore.ID) if err != nil { return nil, fmt.Errorf("failed to find repo by ID: %w", err) } summary, err := c.git.Summary(ctx, git.SummaryParams{ReadParams: git.CreateReadParams(repo)}) if err != nil { return nil, fmt.Errorf("failed to get repo summary: %w", err) } return &types.RepositorySummary{ DefaultBranchCommitCount: summary.CommitCount, BranchCount: summary.BranchCount, TagCount: summary.TagCount, PullReqSummary: types.RepositoryPullReqSummary{ OpenCount: repo.NumOpenPulls, ClosedCount: repo.NumClosedPulls, MergedCount: repo.NumMergedPulls, }, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/create_branch.go
app/api/controller/repo/create_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 repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/audit" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // CreateBranchInput used for branch creation apis. type CreateBranchInput struct { Name string `json:"name"` // Target is the commit (or points to the commit) the new branch will be pointing to. // If no target is provided, the branch points to the same commit as the default branch of the repo. Target string `json:"target"` DryRunRules bool `json:"dry_run_rules"` BypassRules bool `json:"bypass_rules"` } // CreateBranch creates a new branch for a repo. func (c *Controller) CreateBranch(ctx context.Context, session *auth.Session, repoRef string, in *CreateBranchInput, ) (types.CreateBranchOutput, []types.RuleViolations, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return types.CreateBranchOutput{}, nil, err } // set target to default branch in case no target was provided if in.Target == "" { in.Target = repo.DefaultBranch } rules, isRepoOwner, err := c.fetchBranchRules(ctx, session, repo) if err != nil { return types.CreateBranchOutput{}, nil, err } violations, err := rules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: in.BypassRules, IsRepoOwner: isRepoOwner, Repo: repo, RefAction: protection.RefActionCreate, RefType: protection.RefTypeBranch, RefNames: []string{in.Name}, }) if err != nil { return types.CreateBranchOutput{}, nil, fmt.Errorf("failed to verify protection rules: %w", err) } if in.DryRunRules { return types.CreateBranchOutput{ DryRunRulesOutput: types.DryRunRulesOutput{ DryRunRules: true, RuleViolations: violations, }, }, nil, nil } if protection.IsCritical(violations) { return types.CreateBranchOutput{}, violations, nil } writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return types.CreateBranchOutput{}, nil, fmt.Errorf("failed to create RPC write params: %w", err) } rpcOut, err := c.git.CreateBranch(ctx, &git.CreateBranchParams{ WriteParams: writeParams, BranchName: in.Name, Target: in.Target, }) if err != nil { return types.CreateBranchOutput{}, nil, err } branch, err := controller.MapBranch(rpcOut.Branch) if err != nil { return types.CreateBranchOutput{}, nil, fmt.Errorf("failed to map branch: %w", err) } if protection.IsBypassed(violations) { err = c.auditService.Log(ctx, session.Principal, audit.NewResource( audit.ResourceTypeRepository, repo.Identifier, audit.RepoPath, repo.Path, audit.BypassedResourceType, audit.BypassedResourceTypeBranch, audit.BypassedResourceName, branch.Name, audit.BypassAction, audit.BypassActionCreated, audit.ResourceName, fmt.Sprintf( audit.BypassSHALabelFormat, repo.Identifier, branch.Name, ), ), audit.ActionBypassed, paths.Parent(repo.Path), audit.WithNewObject(audit.BranchObject{ BranchName: branch.Name, RepoPath: repo.Path, RuleViolations: violations, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for create branch operation: %s", err) } } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeCreateBranch, Principal: session.Principal.ToPrincipalInfo(), Path: repo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for create branch operation: %s", err) } return types.CreateBranchOutput{ Branch: branch, DryRunRulesOutput: types.DryRunRulesOutput{ RuleViolations: violations, }, }, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/label_value_list.go
app/api/controller/repo/label_value_list.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 repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListLabelValues lists all label values defined for the specified repository. func (c *Controller) ListLabelValues( ctx context.Context, session *auth.Session, repoRef string, key string, filter types.ListQueryFilter, ) ([]*types.LabelValue, int64, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to repo: %w", err) } values, count, err := c.labelSvc.ListValues(ctx, nil, &repo.ID, key, filter) if err != nil { return nil, 0, fmt.Errorf("failed to list repo label values: %w", err) } return values, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/list_branches.go
app/api/controller/repo/list_branches.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 repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/git" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/gotidy/ptr" ) // ListBranches lists the branches of a repo. func (c *Controller) ListBranches(ctx context.Context, session *auth.Session, repoRef string, filter *types.BranchFilter, ) ([]types.BranchExtended, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } rpcOut, err := c.git.ListBranches(ctx, &git.ListBranchesParams{ ReadParams: git.CreateReadParams(repo), IncludeCommit: filter.IncludeCommit, Query: filter.Query, Sort: mapToRPCBranchSortOption(filter.Sort), Order: mapToRPCSortOrder(filter.Order), Page: int32(filter.Page), //nolint:gosec PageSize: int32(filter.Size), //nolint:gosec }) if err != nil { return nil, fmt.Errorf("fail to get the list of branches from git: %w", err) } branches := rpcOut.Branches metadata, err := c.collectBranchMetadata(ctx, repo, branches, filter.BranchMetadataOptions) if err != nil { return nil, fmt.Errorf("fail to collect branch metadata: %w", err) } response := make([]types.BranchExtended, len(branches)) for i := range branches { response[i].Branch, err = controller.MapBranch(branches[i]) if err != nil { return nil, fmt.Errorf("failed to map branch: %w", err) } response[i].IsDefault = repo.DefaultBranch == branches[i].Name metadata.apply(i, &response[i]) } return response, nil } // collectBranchMetadata collects the metadata for the provided list of branches. // The metadata includes check, rules, pull requests, and branch divergences. // Each of these would be returned only if the corresponding option is true. func (c *Controller) collectBranchMetadata( ctx context.Context, repo *types.RepositoryCore, branches []git.Branch, options types.BranchMetadataOptions, ) (branchMetadataOutput, error) { var ( checkSummary map[sha.SHA]types.CheckCountSummary branchRuleMap map[string][]types.RuleInfo pullReqMap map[string][]*types.PullReq divergences *git.GetCommitDivergencesOutput err error ) if options.IncludeChecks { commitSHAs := make([]string, len(branches)) for i := range branches { commitSHAs[i] = branches[i].SHA.String() } checkSummary, err = c.checkStore.ResultSummary(ctx, repo.ID, commitSHAs) if err != nil { return branchMetadataOutput{}, fmt.Errorf("fail to fetch check summary for commits: %w", err) } } if options.IncludeRules { rules, err := c.protectionManager.ListRepoBranchRules(ctx, repo.ID) if err != nil { return branchMetadataOutput{}, fmt.Errorf("failed to fetch protection rules for the repository: %w", err) } branchRuleMap = make(map[string][]types.RuleInfo) for i := range branches { branchName := branches[i].Name branchRuleInfos, err := protection.GetBranchRuleInfos( repo.ID, repo.Identifier, rules, repo.DefaultBranch, branchName, protection.RuleInfoFilterStatusActive, protection.RuleInfoFilterTypeBranch) if err != nil { return branchMetadataOutput{}, fmt.Errorf("failed get branch rule infos: %w", err) } branchRuleMap[branchName] = branchRuleInfos } } if options.IncludePullReqs { branchNames := make([]string, len(branches)) for i := range branches { branchNames[i] = branches[i].Name } pullReqMap, err = c.pullReqStore.ListOpenByBranchName(ctx, repo.ID, branchNames) if err != nil { return branchMetadataOutput{}, fmt.Errorf("fail to fetch pull requests per branch: %w", err) } } if options.MaxDivergence > 0 { readParams := git.CreateReadParams(repo) divergenceRequests := make([]git.CommitDivergenceRequest, len(branches)) for i := range branches { divergenceRequests[i].From = branches[i].Name divergenceRequests[i].To = repo.DefaultBranch } divergences, err = c.git.GetCommitDivergences(ctx, &git.GetCommitDivergencesParams{ ReadParams: readParams, MaxCount: int32(options.MaxDivergence), //nolint:gosec Requests: divergenceRequests, }) if err != nil { return branchMetadataOutput{}, fmt.Errorf("fail to fetch commit divergences: %w", err) } } return branchMetadataOutput{ checkSummary: checkSummary, branchRuleMap: branchRuleMap, pullReqMap: pullReqMap, divergences: divergences, }, nil } type branchMetadataOutput struct { checkSummary map[sha.SHA]types.CheckCountSummary branchRuleMap map[string][]types.RuleInfo pullReqMap map[string][]*types.PullReq divergences *git.GetCommitDivergencesOutput } func (metadata branchMetadataOutput) apply( idx int, branch *types.BranchExtended, ) { if metadata.checkSummary != nil { branch.CheckSummary = ptr.Of(metadata.checkSummary[branch.SHA]) } if metadata.branchRuleMap != nil { branch.Rules = metadata.branchRuleMap[branch.Name] } if metadata.pullReqMap != nil { branch.PullRequests = metadata.pullReqMap[branch.Name] } if metadata.divergences != nil { branch.CommitDivergence = ptr.Of(types.CommitDivergence(metadata.divergences.Divergences[idx])) } } func mapToRPCBranchSortOption(o enum.BranchSortOption) git.BranchSortOption { switch o { case enum.BranchSortOptionDate: return git.BranchSortOptionDate case enum.BranchSortOptionName: return git.BranchSortOptionName case enum.BranchSortOptionDefault: return git.BranchSortOptionDefault default: // no need to error out - just use default for sorting return git.BranchSortOptionDefault } } func mapToRPCSortOrder(o enum.Order) git.SortOrder { switch o { case enum.OrderAsc: return git.SortOrderAsc case enum.OrderDesc: return git.SortOrderDesc case enum.OrderDefault: return git.SortOrderDefault default: // no need to error out - just use default for sorting return git.SortOrderDefault } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false