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/ssh/middleware.go | ssh/middleware.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ssh
import (
"runtime/debug"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/gliderlabs/ssh"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type Middleware func(ssh.Handler) ssh.Handler
// ChainMiddleware combines multiple middleware into a single ssh.Handler.
func ChainMiddleware(handler ssh.Handler, middlewares ...Middleware) ssh.Handler {
for i := len(middlewares) - 1; i >= 0; i-- { // Reverse order to maintain correct chaining
handler = middlewares[i](handler)
}
return handler
}
// PanicRecoverMiddleware wraps the SSH handler to recover from panics and log them.
func PanicRecoverMiddleware(next ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
defer func() {
if r := recover(); r != nil {
// Log the panic and stack trace
// Get the context and logger
ctx := s.Context()
logger := getLogger(ctx)
logger.Error().Msgf("encountered panic while processing ssh operation: %v\n%s", r, debug.Stack())
_, _ = s.Write([]byte("Internal server error. Please try again later.\n"))
}
}()
// Call the next handler
next(s)
}
}
func HLogAccessLogHandler(next ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
start := time.Now()
user := s.User()
remoteAddr := s.RemoteAddr()
command := s.Command()
// Get the context and logger
ctx := s.Context()
logger := getLogger(ctx)
// Log session start
logger.Info().
Str("ssh.user", user).
Str("ssh.remote", remoteAddr.String()).
Strs("ssh.command", command).
Msg("SSH session started")
// Call the next handler
next(s)
// Log session completion
duration := time.Since(start)
logger.Info().
Dur("ssh.elapsed_ms", duration).
Str("ssh.user", user).
Msg("SSH session completed")
}
}
func HLogRequestIDHandler(next ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
sshCtx := s.Context() // This is ssh.Context
reqID := getRequestID(sshCtx.SessionID())
request.WithRequestIDSSH(sshCtx, reqID)
log := getLoggerWithRequestID(reqID)
sshCtx.SetValue(loggerKey, log)
// continue serving request
next(s)
}
}
type PublicKeyMiddleware func(next ssh.PublicKeyHandler) ssh.PublicKeyHandler
func ChainPublicKeyMiddleware(handler ssh.PublicKeyHandler, middlewares ...PublicKeyMiddleware) ssh.PublicKeyHandler {
for i := len(middlewares) - 1; i >= 0; i-- { // Reverse order for correct chaining
handler = middlewares[i](handler)
}
return handler
}
func LogPublicKeyMiddleware(next ssh.PublicKeyHandler) ssh.PublicKeyHandler {
return func(ctx ssh.Context, key ssh.PublicKey) bool {
reqID := getRequestID(ctx.SessionID())
request.WithRequestIDSSH(ctx, reqID)
log := getLoggerWithRequestID(reqID)
start := time.Now()
log.Info().
Str("ssh.user", ctx.User()).
Str("ssh.remote", ctx.RemoteAddr().String()).
Msg("Public key authentication attempt")
v := next(ctx, key)
// Log session completion
duration := time.Since(start)
log.Info().
Dur("ssh.elapsed_ms", duration).
Str("ssh.user", ctx.User()).
Msg("Public key authentication attempt completed")
return v
}
}
func getLogger(ctx ssh.Context) zerolog.Logger {
logger, ok := ctx.Value(loggerKey).(zerolog.Logger)
if !ok {
logger = log.Logger
}
return logger
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/ssh/log.go | ssh/log.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 ssh
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const loggerKey contextKey = "logger"
func getRequestID(reqID string) string {
if len(reqID) > 20 {
reqID = reqID[:20]
}
return reqID
}
func getLoggerWithRequestID(sessionID string) zerolog.Logger {
return log.Logger.With().Str("request_id", getRequestID(sessionID)).Logger()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/ssh/server.go | ssh/server.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 ssh
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"io/fs"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/harness/gitness/app/api/controller/lfs"
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/services/publickey"
"github.com/harness/gitness/app/services/publickey/keyssh"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/gliderlabs/ssh"
"github.com/rs/zerolog/log"
gossh "golang.org/x/crypto/ssh"
"golang.org/x/exp/slices"
)
type contextKey string
const principalKey = contextKey("principalKey")
var (
allowedCommands = []string{
"git-upload-pack",
"git-receive-pack",
"git-lfs-authenticate",
"git-lfs-transfer",
}
defaultCiphers = []string{
"chacha20-poly1305@openssh.com",
"aes128-ctr",
"aes192-ctr",
"aes256-ctr",
"aes128-gcm@openssh.com",
"aes256-gcm@openssh.com",
}
defaultKeyExchanges = []string{
"curve25519-sha256",
"curve25519-sha256@libssh.org",
"ecdh-sha2-nistp256",
"ecdh-sha2-nistp384",
"ecdh-sha2-nistp521",
"diffie-hellman-group14-sha256",
"diffie-hellman-group14-sha1",
}
defaultMACs = []string{
"hmac-sha2-256-etm@openssh.com",
"hmac-sha2-512-etm@openssh.com",
"hmac-sha2-256",
"hmac-sha2-512",
}
KeepAliveMsg = "keepalive@openssh.com"
)
type Server struct {
internal *ssh.Server
Host string
Port int
DefaultUser string
TrustedUserCAKeys []string
TrustedUserCAKeysParsed []gossh.PublicKey
Ciphers []string
KeyExchanges []string
MACs []string
HostKeys []string
KeepAliveInterval time.Duration
Verifier publickey.SSHAuthService
RepoCtrl *repo.Controller
LFSCtrl *lfs.Controller
ServerKeyPath string
}
func (s *Server) sanitize() error {
if s.Port == 0 {
s.Port = 22
}
if len(s.Ciphers) == 0 {
s.Ciphers = defaultCiphers
}
if len(s.KeyExchanges) == 0 {
s.KeyExchanges = defaultKeyExchanges
}
if len(s.MACs) == 0 {
s.MACs = defaultMACs
}
if s.KeepAliveInterval == 0 {
s.KeepAliveInterval = 5000
}
if s.RepoCtrl == nil {
return errors.InvalidArgument("repository controller is needed to run git service pack commands")
}
return nil
}
func (s *Server) ListenAndServe() error {
err := s.sanitize()
if err != nil {
return fmt.Errorf("failed to sanitize server defaults: %w", err)
}
s.internal = &ssh.Server{
Addr: net.JoinHostPort(s.Host, strconv.Itoa(s.Port)),
Handler: ChainMiddleware(
s.sessionHandler,
PanicRecoverMiddleware,
HLogRequestIDHandler,
HLogAccessLogHandler,
),
PublicKeyHandler: ChainPublicKeyMiddleware(
s.publicKeyHandler,
LogPublicKeyMiddleware,
),
PtyCallback: func(ssh.Context, ssh.Pty) bool {
return false
},
ConnectionFailedCallback: sshConnectionFailed,
ServerConfigCallback: func(ssh.Context) *gossh.ServerConfig {
config := &gossh.ServerConfig{}
config.KeyExchanges = s.KeyExchanges
config.MACs = s.MACs
config.Ciphers = s.Ciphers
return config
},
}
err = s.setupHostKeys()
if err != nil {
return fmt.Errorf("failed to setup host keys: %w", err)
}
log.Debug().Msgf("starting ssh service....: %v", s.internal.Addr)
err = s.internal.ListenAndServe()
if err != nil {
return fmt.Errorf("ssh service not running: %w", err)
}
return nil
}
func (s *Server) setupHostKeys() error {
keys := make([]string, 0, len(s.HostKeys))
for _, key := range s.HostKeys {
_, err := os.Stat(key)
if err != nil {
return fmt.Errorf("failed to read provided host key %q: %w", key, err)
}
keys = append(keys, key)
}
if len(keys) == 0 {
log.Debug().Msg("no host key provided - setup default key if it doesn't exist yet")
err := CreateKeyIfNotExists(s.ServerKeyPath)
if err != nil {
return fmt.Errorf("failed to setup default key %q: %w", s.ServerKeyPath, err)
}
keys = append(keys, s.ServerKeyPath)
}
// set keys to internal ssh server
for _, key := range keys {
err := s.internal.SetOption(ssh.HostKeyFile(key))
if err != nil {
log.Err(err).Msg("failed to set host key to ssh server")
}
}
return nil
}
func (s *Server) Shutdown(ctx context.Context) error {
log.Debug().Msgf("stopping ssh service: %v", s.internal.Addr)
err := s.internal.Shutdown(ctx)
if err != nil {
return fmt.Errorf("failed to stop ssh service: %w", err)
}
return nil
}
func (s *Server) sessionHandler(session ssh.Session) {
command := session.RawCommand()
principal, ok := session.Context().Value(principalKey).(*types.PrincipalInfo)
if !ok {
_, _ = fmt.Fprintf(session.Stderr(), "principal not found or empty")
return
}
parts := strings.Fields(command)
if len(parts) < 2 {
_, _ = fmt.Fprintf(session.Stderr(), "command %q must have an argument\n", command)
return
}
// first part is git service pack command: git-upload-pack, git-receive-pack
// of git-lfs client command: git-lfs-authenticate, git-lfs-transfer
gitCommand := parts[0]
if !slices.Contains(allowedCommands, gitCommand) {
_, _ = fmt.Fprintf(session.Stderr(), "command not supported: %q\n", command)
return
}
// handle git-lfs commands
//nolint:nestif
if strings.HasPrefix(gitCommand, "git-lfs-") {
gitLFSservice, err := enum.ParseGitLFSServiceType(gitCommand)
if err != nil {
_, _ = fmt.Fprintf(session.Stderr(), "failed to parse git-lfs service command: %q\n", gitCommand)
return
}
repoRef := getRepoRefFromCommand(parts[1])
// when git-lfs-transfer not supported, git-lfs client uses git-lfs-authenticate
// to gain a token from server and continue with http transfer APIs
if gitLFSservice == enum.GitLFSServiceTypeTransfer {
_, _ = fmt.Fprint(session.Stderr(), "git-lfs-transfer is not supported.")
return
}
// handling git-lfs-authenticate
principal := types.Principal{
ID: principal.ID,
UID: principal.UID,
Email: principal.Email,
Type: principal.Type,
DisplayName: principal.DisplayName,
Created: principal.Created,
Updated: principal.Updated,
}
ctx, cancel := context.WithCancel(session.Context())
defer cancel()
response, err := s.LFSCtrl.Authenticate(
ctx,
&auth.Session{
Principal: principal,
},
repoRef)
if err != nil {
log.Error().Err(err).Msg("git lfs authenticate failed")
writeErrorToSession(session, err.Error())
return
}
responseJSON, err := json.Marshal(response)
if err != nil {
log.Error().Err(err).Msg("failed to marshal lfs authenticate response")
writeErrorToSession(session, err.Error())
return
}
if _, err := session.Write(responseJSON); err != nil {
log.Error().Err(err).Msg("failed to write response of git lfs authenticate")
writeErrorToSession(session, err.Error())
}
return
}
// handle git service pack commands
gitServicePack := strings.TrimPrefix(gitCommand, "git-")
service, err := enum.ParseGitServiceType(gitServicePack)
if err != nil {
_, _ = fmt.Fprintf(session.Stderr(), "failed to parse service pack: %q\n", gitServicePack)
return
}
// git command args
gitArgs := parts[1:]
repoRef := getRepoRefFromCommand(gitArgs[0])
gitProtocol := ""
for _, key := range session.Environ() {
if strings.HasPrefix(key, "GIT_PROTOCOL=") {
gitProtocol = key[len("GIT_PROTOCOL="):]
}
}
ctx, cancel := context.WithCancel(session.Context())
defer cancel()
log := log.Logger.With().Logger()
ctx = request.WithRequestID(ctx, getRequestID(session.Context().SessionID()))
ctx = log.WithContext(ctx)
// set keep alive connection
if s.KeepAliveInterval > 0 {
go sendKeepAliveMsg(ctx, session, s.KeepAliveInterval)
}
err = s.RepoCtrl.GitServicePack(
ctx,
&auth.Session{
Principal: types.Principal{
ID: principal.ID,
UID: principal.UID,
Email: principal.Email,
Type: principal.Type,
DisplayName: principal.DisplayName,
Created: principal.Created,
Updated: principal.Updated,
},
},
repoRef,
api.ServicePackOptions{
Service: service,
Stdout: session,
Stdin: session,
Stderr: session.Stderr(),
Protocol: gitProtocol,
StatelessRPC: false,
},
)
if err != nil {
log.Error().Err(err).Msg("git service pack failed")
_, writeErr := io.Copy(session.Stderr(), strings.NewReader(err.Error()))
if writeErr != nil && !errors.Is(writeErr, io.ErrClosedPipe) {
log.Warn().Err(writeErr).Msg("error writing to session stderr")
}
}
}
func sendKeepAliveMsg(ctx context.Context, session ssh.Session, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
log.Ctx(ctx).Debug().Str("remote_addr", session.RemoteAddr().String()).Msgf("sendKeepAliveMsg")
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
log.Ctx(ctx).Debug().Msg("send keepalive message to ssh client")
_, err := session.SendRequest(KeepAliveMsg, true, nil)
if err != nil {
log.Ctx(ctx).Debug().Err(err).Msg("failed to send keepalive message to ssh client")
}
}
}
}
func (s *Server) publicKeyHandler(ctx ssh.Context, key ssh.PublicKey) bool {
log := getLoggerWithRequestID(ctx.SessionID())
request.WithRequestIDSSH(ctx, getRequestID(ctx.SessionID()))
if slices.Contains(keyssh.DisallowedTypes, key.Type()) {
log.Warn().Msgf("public key type not supported: %s", key.Type())
return false
}
if s.DefaultUser != "" && ctx.User() != s.DefaultUser {
log.Warn().Msgf("invalid SSH username %s - must use %s for all git operations via ssh",
ctx.User(), s.DefaultUser)
log.Warn().Msgf("failed authentication attempt from %s", ctx.RemoteAddr())
return false
}
principal, err := s.Verifier.ValidateKey(ctx, ctx.User(), key)
if errors.IsNotFound(err) {
log.Debug().Err(err).Msg("public key is unknown")
return false
}
if err != nil {
log.Warn().Err(err).Msg("failed to validate public key")
return false
}
log.Debug().Msg("public key verified")
// check if we have a certificate
if cert, ok := key.(*gossh.Certificate); ok {
if len(s.TrustedUserCAKeys) == 0 {
log.Warn().Msg("Certificate Rejected: No trusted certificate authorities for this server")
log.Warn().Msgf("Failed authentication attempt from %s", ctx.RemoteAddr())
return false
}
if cert.CertType != gossh.UserCert {
log.Warn().Msg("Certificate Rejected: Not a user certificate")
log.Warn().Msgf("Failed authentication attempt from %s", ctx.RemoteAddr())
return false
}
certChecker := &gossh.CertChecker{}
if err := certChecker.CheckCert(principal.UID, cert); err != nil {
return false
}
}
ctx.SetValue(principalKey, principal)
return true
}
func sshConnectionFailed(conn net.Conn, err error) {
log.Err(err).Msgf("failed connection from %s with error: %v", conn.RemoteAddr(), err)
}
func CreateKeyIfNotExists(path string) error {
_, err := os.Stat(path)
if err == nil {
// if the path already exists there's nothing we have to do
return nil
}
if !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("failed to check for for existence of key: %w", err)
}
log.Debug().Msgf("generate new key at %q", path)
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create dir %q for key: %w", dir, err)
}
err = GenerateKeyPair(path)
if err != nil {
return fmt.Errorf("failed to generate key pair: %w", err)
}
return nil
}
// GenerateKeyPair make a pair of public and private keys for SSH access.
func GenerateKeyPair(keyPath string) error {
privateKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return err
}
privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return err
}
defer f.Close()
if err := pem.Encode(f, privateKeyPEM); err != nil {
return err
}
// generate public key
pub, err := gossh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return err
}
public := gossh.MarshalAuthorizedKey(pub)
p, err := os.OpenFile(keyPath+".pub", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return err
}
defer p.Close()
_, err = p.Write(public)
if err != nil {
return fmt.Errorf("failed to write to public key: %w", err)
}
return nil
}
func getRepoRefFromCommand(gitArg string) string {
// first git service pack cmd arg is path: 'space/repository.git' so we need to remove
// single quotes.
repoRef := strings.Trim(gitArg, "'")
// remove .git suffix
repoRef = strings.TrimSuffix(repoRef, ".git")
return repoRef
}
func writeErrorToSession(session ssh.Session, message string) {
if _, err := io.Copy(session.Stderr(), strings.NewReader(message+"\n")); err != nil {
log.Printf("error writing to session stderr: %v", err)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/contextutil/contextutil_test.go | contextutil/contextutil_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 contextutil
import (
"context"
"testing"
"time"
)
func TestWithNewTimeout(t *testing.T) {
t.Run("creates new context with timeout", func(t *testing.T) {
ctx := context.Background()
timeout := 100 * time.Millisecond
newCtx, cancel := WithNewTimeout(ctx, timeout)
defer cancel()
if newCtx == nil {
t.Fatal("expected non-nil context")
}
deadline, ok := newCtx.Deadline()
if !ok {
t.Fatal("expected context to have deadline")
}
expectedDeadline := time.Now().Add(timeout)
if deadline.After(expectedDeadline.Add(50 * time.Millisecond)) {
t.Errorf("deadline is too far in the future: got %v, expected around %v", deadline, expectedDeadline)
}
})
t.Run("new context is not canceled when parent is canceled", func(t *testing.T) {
parentCtx, parentCancel := context.WithCancel(context.Background())
timeout := 1 * time.Second
newCtx, cancel := WithNewTimeout(parentCtx, timeout)
defer cancel()
// Cancel parent context
parentCancel()
// Give it a moment to propagate
time.Sleep(10 * time.Millisecond)
// New context should not be canceled
select {
case <-newCtx.Done():
t.Fatal("new context should not be canceled when parent is canceled")
default:
// Expected: context is not canceled
}
})
t.Run("new context times out after specified duration", func(t *testing.T) {
ctx := context.Background()
timeout := 50 * time.Millisecond
newCtx, cancel := WithNewTimeout(ctx, timeout)
defer cancel()
select {
case <-newCtx.Done():
t.Fatal("context should not be done immediately")
case <-time.After(10 * time.Millisecond):
// Expected: context is not done yet
}
// Wait for timeout
select {
case <-newCtx.Done():
// Expected: context is done after timeout
if newCtx.Err() != context.DeadlineExceeded {
t.Errorf("expected DeadlineExceeded error, got %v", newCtx.Err())
}
case <-time.After(100 * time.Millisecond):
t.Fatal("context should have timed out")
}
})
t.Run("cancel function works correctly", func(t *testing.T) {
ctx := context.Background()
timeout := 1 * time.Second
newCtx, cancel := WithNewTimeout(ctx, timeout)
// Cancel immediately
cancel()
select {
case <-newCtx.Done():
// Expected: context is canceled
if newCtx.Err() != context.Canceled {
t.Errorf("expected Canceled error, got %v", newCtx.Err())
}
case <-time.After(100 * time.Millisecond):
t.Fatal("context should have been canceled")
}
})
t.Run("zero timeout", func(t *testing.T) {
ctx := context.Background()
timeout := 0 * time.Second
newCtx, cancel := WithNewTimeout(ctx, timeout)
defer cancel()
// Context with zero timeout should be immediately done
select {
case <-newCtx.Done():
// Expected: context is done
case <-time.After(100 * time.Millisecond):
t.Fatal("context with zero timeout should be immediately done")
}
})
t.Run("negative timeout", func(t *testing.T) {
ctx := context.Background()
timeout := -1 * time.Second
newCtx, cancel := WithNewTimeout(ctx, timeout)
defer cancel()
// Context with negative timeout should be immediately done
select {
case <-newCtx.Done():
// Expected: context is done
case <-time.After(100 * time.Millisecond):
t.Fatal("context with negative timeout should be immediately done")
}
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/contextutil/contextutil.go | contextutil/contextutil.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 contextutil
import (
"context"
"time"
)
// WithNewTimeout creates a new context derived from original context, but without canceling and with the new timeout.
func WithNewTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
return context.WithTimeout(context.WithoutCancel(ctx), timeout)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/git.go | types/git.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 types
import (
"time"
gitenum "github.com/harness/gitness/git/enum"
"github.com/harness/gitness/git/sha"
"github.com/harness/gitness/types/enum"
)
const NilSHA = "0000000000000000000000000000000000000000"
// PaginationFilter stores pagination query parameters.
type PaginationFilter struct {
Page int `json:"page"`
Limit int `json:"limit"`
}
// CommitFilter stores commit query parameters.
type CommitFilter struct {
PaginationFilter
After string `json:"after"`
Path string `json:"path"`
Since int64 `json:"since"`
Until int64 `json:"until"`
Committer string `json:"committer"`
CommitterIDs []int64 `json:"committer_ids"`
Author string `json:"author"`
AuthorIDs []int64 `json:"author_ids"`
IncludeStats bool `json:"include_stats"`
}
type BranchMetadataOptions struct {
IncludeChecks bool `json:"include_checks"`
IncludeRules bool `json:"include_rules"`
IncludePullReqs bool `json:"include_pullreqs"`
MaxDivergence int `json:"max_divergence"`
}
// BranchFilter stores branch query parameters.
type BranchFilter struct {
Query string `json:"query"`
Sort enum.BranchSortOption `json:"sort"`
Order enum.Order `json:"order"`
Page int `json:"page"`
Size int `json:"size"`
IncludeCommit bool `json:"include_commit"`
BranchMetadataOptions
}
// TagFilter stores commit tag query parameters.
type TagFilter struct {
Query string `json:"query"`
Sort enum.TagSortOption `json:"sort"`
Order enum.Order `json:"order"`
Page int `json:"page"`
Size int `json:"size"`
}
type ChangeStats struct {
Insertions int64 `json:"insertions"`
Deletions int64 `json:"deletions"`
Changes int64 `json:"changes"`
}
type CommitFileStats struct {
Path string `json:"path"`
OldPath string `json:"old_path,omitempty"`
Status gitenum.FileDiffStatus `json:"status"`
ChangeStats
}
type CommitStats struct {
Total ChangeStats `json:"total"`
Files []CommitFileStats `json:"files,omitempty"`
}
type Commit struct {
SHA sha.SHA `json:"sha"`
TreeSHA sha.SHA `json:"-"`
ParentSHAs []sha.SHA `json:"parent_shas,omitempty"`
Title string `json:"title"`
Message string `json:"message"`
Author Signature `json:"author"`
Committer Signature `json:"committer"`
SignedData *SignedData `json:"-"`
Stats *CommitStats `json:"stats,omitempty"`
Signature *GitSignatureResult `json:"signature"`
}
func (c *Commit) GetSHA() sha.SHA { return c.SHA }
func (c *Commit) SetSignature(sig *GitSignatureResult) { c.Signature = sig }
func (c *Commit) GetSigner() *Signature { return &c.Committer }
func (c *Commit) GetSignedData() *SignedData { return c.SignedData }
type CommitTag struct {
Name string `json:"name"`
SHA sha.SHA `json:"sha"`
IsAnnotated bool `json:"is_annotated"`
Title string `json:"title,omitempty"`
Message string `json:"message,omitempty"`
Tagger *Signature `json:"tagger,omitempty"`
SignedData *SignedData `json:"-"`
Commit *Commit `json:"commit,omitempty"`
Signature *GitSignatureResult `json:"signature"`
}
func (t *CommitTag) GetSHA() sha.SHA { return t.SHA }
func (t *CommitTag) SetSignature(sig *GitSignatureResult) { t.Signature = sig }
func (t *CommitTag) GetSigner() *Signature { return t.Tagger }
func (t *CommitTag) GetSignedData() *SignedData { return t.SignedData }
type Signature struct {
Identity Identity `json:"identity"`
When time.Time `json:"when"`
}
type Identity struct {
Name string `json:"name"`
Email string `json:"email"`
}
type SignedData struct {
Type string
Signature []byte
SignedContent []byte
}
type RenameDetails struct {
OldPath string `json:"old_path"`
NewPath string `json:"new_path"`
CommitShaBefore string `json:"commit_sha_before"`
CommitShaAfter string `json:"commit_sha_after"`
}
type ListCommitResponse struct {
Commits []*Commit `json:"commits"`
RenameDetails []RenameDetails `json:"rename_details"`
TotalCommits int `json:"total_commits,omitempty"`
}
type GitSignatureResult struct {
RepoID int64 `json:"-"`
ObjectSHA sha.SHA `json:"-"`
ObjectTime int64 `json:"-"`
// Created is the timestamp when the signature was first verified.
Created int64 `json:"created,omitempty"`
// Updated is the timestamp when result has been updated (i.e. because of key revocation).
Updated int64 `json:"updated,omitempty"`
// Result is the result of the signature verification.
Result enum.GitSignatureResult `json:"result"`
// PrincipalID is owner of the key with which signature has been checked.
PrincipalID int64 `json:"-"`
KeyScheme enum.PublicKeyScheme `json:"key_scheme,omitempty"`
// KeyID is the ID of the key with which signature has been checked.
KeyID string `json:"key_id,omitempty"`
// KeyFingerprint is the fingerprint of the key with which signature has been checked.
KeyFingerprint string `json:"key_fingerprint,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/devcontainer_config.go | types/devcontainer_config.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 types
import (
"encoding/csv"
"encoding/json"
"fmt"
"net/url"
"path/filepath"
"strings"
"github.com/harness/gitness/types/enum"
"oras.land/oras-go/v2/registry"
)
const FeatureDefaultTag = "latest"
//nolint:tagliatelle
type DevcontainerConfig struct {
Image string `json:"image,omitempty"`
PostCreateCommand LifecycleCommand `json:"postCreateCommand"`
PostStartCommand LifecycleCommand `json:"postStartCommand"`
ForwardPorts []json.Number `json:"forwardPorts,omitempty"`
ContainerEnv map[string]string `json:"containerEnv,omitempty"`
Customizations DevContainerConfigCustomizations `json:"customizations,omitempty"`
RunArgs []string `json:"runArgs,omitempty"`
ContainerUser string `json:"containerUser,omitempty"`
RemoteUser string `json:"remoteUser,omitempty"`
Features *Features `json:"features,omitempty"`
OverrideFeatureInstallOrder []string `json:"overrideFeatureInstallOrder,omitempty"`
Privileged *bool `json:"privileged,omitempty"`
Init *bool `json:"init,omitempty"`
CapAdd []string `json:"capAdd,omitempty"`
SecurityOpt []string `json:"securityOpt,omitempty"`
Mounts []*Mount `json:"mounts,omitempty"`
}
// Constants for discriminator values.
const (
TypeString = "string"
TypeArray = "array"
TypeCommandMap = "commandMap"
)
//nolint:tagliatelle
type LifecycleCommand struct {
CommandString string `json:"commandString,omitempty"`
CommandArray []string `json:"commandArray,omitempty"`
CommandMap map[string]any `json:"commandMap,omitempty"`
Discriminator string `json:"-"` // Tracks the original type for proper re-marshaling
}
func (lc *LifecycleCommand) UnmarshalJSON(data []byte) error {
// Try to unmarshal as a single string
var commandStr string
if err := json.Unmarshal(data, &commandStr); err == nil {
lc.CommandString = commandStr
lc.Discriminator = TypeString
return nil
}
// Try to unmarshal as an array of strings
var commandArr []string
if err := json.Unmarshal(data, &commandArr); err == nil {
lc.CommandArray = commandArr
lc.Discriminator = TypeArray
return nil
}
// Try to unmarshal as a map with mixed types
var rawMap map[string]any
if err := json.Unmarshal(data, &rawMap); err == nil {
for key, value := range rawMap {
switch v := value.(type) {
case string:
// Valid string value
case []any:
// Convert []interface{} to []string
var strArray []string
for _, item := range v {
if str, ok := item.(string); ok {
strArray = append(strArray, str)
} else {
return fmt.Errorf("invalid format: array contains non-string value")
}
}
rawMap[key] = strArray
default:
return fmt.Errorf("invalid format: map contains unsupported type")
}
}
lc.CommandMap = rawMap
lc.Discriminator = TypeCommandMap
return nil
}
return fmt.Errorf("invalid format: must be string, []string, or map[string]any")
}
func (lc *LifecycleCommand) MarshalJSON() ([]byte, error) {
// If Discriminator is empty, return an empty JSON object (i.e., {} or no content)
if lc.Discriminator == "" || lc == nil {
return []byte("{}"), nil
}
switch lc.Discriminator {
case TypeString:
return json.Marshal(lc.CommandString)
case TypeArray:
return json.Marshal(lc.CommandArray)
case TypeCommandMap:
return json.Marshal(lc.CommandMap)
default:
return nil, fmt.Errorf("unknown type for LifecycleCommand")
}
}
// ToCommandArray converts the LifecycleCommand into a slice of full commands.
func (lc *LifecycleCommand) ToCommandArray() []string {
// If Discriminator is empty, return nil
if lc.Discriminator == "" || lc == nil {
return nil
}
switch lc.Discriminator {
case TypeString:
return []string{lc.CommandString}
case TypeArray:
return []string{strings.Join(lc.CommandArray, " ")}
case TypeCommandMap:
var commands []string
for _, value := range lc.CommandMap {
switch v := value.(type) {
case string:
commands = append(commands, v)
case []string:
commands = append(commands, strings.Join(v, " "))
}
}
return commands
default:
return nil
}
}
type Features map[string]*FeatureValue
type FeatureValue struct {
Source string `json:"source,omitempty"`
SourceType enum.FeatureSourceType `json:"source_type,omitempty"`
Options map[string]any `json:"options,omitempty"`
}
func (f *FeatureValue) UnmarshalJSON(data []byte) error {
var version string
if err := json.Unmarshal(data, &version); err == nil {
f.Options = make(map[string]any)
f.Options["version"] = version
return nil
}
var options map[string]any
if err := json.Unmarshal(data, &options); err == nil {
for key, value := range options {
switch value.(type) {
case string, bool:
continue
default:
return fmt.Errorf("invalid type for option '%s': must be string or boolean, got %T", key, value)
}
}
f.Options = options
return nil
}
return nil
}
func (f *FeatureValue) MarshalJSON() ([]byte, error) {
return json.Marshal(f.Options)
}
func (f *Features) UnmarshalJSON(data []byte) error {
if *f == nil {
*f = make(Features)
}
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
for key, value := range raw {
sanitizedSource, sourceType, validationErr := validateFeatureSource(key)
if validationErr != nil {
return validationErr
}
feature := &FeatureValue{Source: sanitizedSource, SourceType: sourceType}
if err := json.Unmarshal(value, feature); err != nil {
return fmt.Errorf("failed to unmarshal feature '%s': %w", key, err)
}
(*f)[sanitizedSource] = feature
}
return nil
}
func validateFeatureSource(source string) (string, enum.FeatureSourceType, error) {
if _, err := registry.ParseReference(source); err == nil {
indexOfSeparator := strings.Index(source, ":")
if indexOfSeparator == -1 {
source += ":" + FeatureDefaultTag
}
return source, enum.FeatureSourceTypeOCI, nil
}
if err := validateTarballURL(source); err == nil {
return source, enum.FeatureSourceTypeTarball, nil
}
return source, enum.FeatureSourceTypeLocal, fmt.Errorf("unsupported feature source: %s", source)
}
func validateTarballURL(source string) error {
tarballURL, err := url.Parse(source)
if err != nil {
return fmt.Errorf("parsing feature URL: %w", err)
}
if tarballURL.Scheme != "http" && tarballURL.Scheme != "https" {
return fmt.Errorf("invalid feature URL: %s", tarballURL.String())
}
if !strings.HasSuffix(tarballURL.Path, ".tgz") {
return fmt.Errorf("invalid feature URL: %s", tarballURL.String())
}
return nil
}
type Mount struct {
Source string `json:"source,omitempty"`
Target string `json:"target,omitempty"`
Type string `json:"type,omitempty"`
}
func (m *Mount) UnmarshalJSON(data []byte) error {
type Alias Mount
aux := &struct {
*Alias
}{
Alias: (*Alias)(m),
}
if err := json.Unmarshal(data, &aux); err == nil {
return nil
}
var str string
if err := json.Unmarshal(data, &str); err == nil {
dst, err := stringToObject(str)
if err != nil {
return err
}
*m = *dst
return nil
}
return fmt.Errorf("failed to unmarshal JSON: %s", string(data))
}
func ParseMountsFromRawSlice(values []any) ([]*Mount, error) {
var mounts []*Mount
for _, value := range values {
switch v := value.(type) {
case *Mount:
mounts = append(mounts, v)
case map[string]any:
// when coming from unmarshal
mount := &Mount{}
if src, ok := v["source"].(string); ok {
mount.Source = src
}
if tgt, ok := v["target"].(string); ok {
mount.Target = tgt
}
if typ, ok := v["type"].(string); ok {
mount.Type = typ
}
mounts = append(mounts, mount)
case string: // when it’s a raw "ap[...]" string
dst, err := stringToObject(v)
if err != nil {
return nil, err
}
mounts = append(mounts, dst)
default:
return nil, fmt.Errorf("invalid mount value: %+v (type %T)", value, value)
}
}
return mounts, nil
}
func ParseMountsFromStringSlice(values []string) ([]*Mount, error) {
var mounts []*Mount
for _, value := range values {
dst, err := stringToObject(value)
if err != nil {
return nil, err
}
mounts = append(mounts, dst)
}
return mounts, nil
}
func stringToObject(mountStr string) (*Mount, error) {
csvReader := csv.NewReader(strings.NewReader(mountStr))
fields, err := csvReader.Read()
if err != nil {
return nil, err
}
newMount := Mount{Type: "volume"}
for _, field := range fields {
key, val, ok := strings.Cut(field, "=")
key = strings.ToLower(key)
if !ok {
return nil, fmt.Errorf("invalid format for mount field: %s", field)
}
switch key {
case "type":
newMount.Type = strings.ToLower(val)
case "source", "src":
newMount.Source = val
if strings.HasPrefix(val, "."+string(filepath.Separator)) || val == "." {
if abs, err := filepath.Abs(val); err == nil {
newMount.Source = abs
}
}
case "target", "dst", "destination":
newMount.Target = val
}
}
return &newMount, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/lfs.go | types/lfs.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
type LFSObject struct {
ID int64 `json:"id"`
OID string `json:"oid"`
Size int64 `json:"size"`
Created int64 `json:"created"`
CreatedBy int64 `json:"created_by"`
RepoID int64 `json:"repo_id"`
}
type LFSLock struct {
ID int64 `json:"id"`
Path string `json:"path"`
Ref string `json:"ref"`
Created int64 `json:"created"`
RepoID int64 `json:"repo_id"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/cde_gateway.go | types/cde_gateway.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 types
const GatewayHealthHealthy = "healthy"
const GatewayHealthUnhealthy = "unhealthy"
const GatewayHealthUnknown = "unknown"
type CDEGatewayStats struct {
Name string `json:"name"`
GroupName string `json:"group_name"`
Region string `json:"region"`
Zone string `json:"zone"`
Health string `json:"health"`
EnvoyHealth string `json:"envoy_health"`
Version string `json:"version"`
}
type CDEGateway struct {
CDEGatewayStats
SpaceID int64 `json:"space_id,omitempty"`
SpacePath string `json:"space_path"`
InfraProviderConfigID int64 `json:"infra_provider_config_id,omitempty"`
InfraProviderConfigIdentifier string `json:"infra_provider_config_identifier"`
OverallHealth string `json:"overall_health,omitempty"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
}
type CDEGatewayFilter struct {
IsLatest bool `json:"is_latest,omitempty"`
Health string `json:"health,omitempty"`
HealthReportValidityInMins int `json:"health_report_validity_in_mins,omitempty"`
InfraProviderConfigIDs []int64 `json:"infra_provider_config_ids,omitempty"`
InfraProviderConfigIdentifiers []string `json:"infra_provider_config_identifiers,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/commit.go | types/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 types
import (
"github.com/harness/gitness/git/sha"
)
// CommitFilesResponse holds commit id.
type CommitFilesResponse struct {
CommitID sha.SHA `json:"commit_id"`
DryRunRulesOutput
ChangedFiles []FileReference `json:"changed_files"`
}
type FileReference struct {
Path string `json:"path"`
SHA sha.SHA `json:"blob_sha"`
}
type PathDetails struct {
Path string `json:"path"`
LastCommit *Commit `json:"last_commit,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/types_test.go | types/types_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 types
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/ide.go | types/ide.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
type IDEDownloadURLs struct {
Arm64Sha string
Amd64Sha string
Arm64 string
Amd64 string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/infra_provider.go | types/infra_provider.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 types
import (
"fmt"
"strconv"
"strings"
"github.com/harness/gitness/types/enum"
"github.com/docker/go-units"
)
type InfraProviderConfig struct {
ID int64 `json:"-"`
Identifier string `json:"identifier"`
Name string `json:"name"`
Type enum.InfraProviderType `json:"type"`
Metadata map[string]any `json:"metadata"`
Resources []InfraProviderResource `json:"resources"`
SpaceID int64 `json:"-"`
SpacePath string `json:"space_path"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
SetupYAML string `json:"setup_yaml,omitempty"`
IsDeleted bool `json:"is_deleted,omitempty"`
Deleted *int64 `json:"deleted,omitempty"`
}
type InfraProviderResource struct {
ID int64 `json:"-"`
UID string `json:"identifier"`
Name string `json:"name"`
InfraProviderConfigID int64 `json:"-"`
InfraProviderConfigIdentifier string `json:"config_identifier"`
InfraProviderConfigName string `json:"config_name"`
CPU *string `json:"cpu"`
Memory *string `json:"memory"`
Disk *string `json:"disk"`
Network *string `json:"network"`
Region string `json:"region"`
Metadata map[string]string `json:"metadata"`
SpaceID int64 `json:"-"`
SpacePath string `json:"space_path"`
InfraProviderType enum.InfraProviderType `json:"infra_provider_type"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
IsDeleted bool `json:"is_deleted,omitempty"`
Deleted *int64 `json:"deleted,omitempty"`
}
func (i *InfraProviderResource) Identifier() int64 {
return i.ID
}
func validateInfraProviderResource(a InfraProviderResource) error {
err := validateCPU(a.CPU)
if err != nil {
return err
}
err = validateBytes(a.Memory)
if err != nil {
return err
}
err = validateBytes(a.Disk)
if err != nil {
return err
}
return nil
}
func validateBytes(bytes *string) error {
if bytes == nil {
return fmt.Errorf("bytes is required")
}
intValue, err := units.RAMInBytes(withoutSpace(*bytes))
if err != nil {
return err
}
if intValue < 0 {
return fmt.Errorf("bytes must be positive")
}
return nil
}
func withoutSpace(str string) string {
return strings.ReplaceAll(str, " ", "")
}
func validateCPU(cpu *string) error {
if cpu == nil {
return fmt.Errorf("cpu is required")
}
intValue, err := strconv.Atoi(withoutSpace(*cpu))
if err != nil {
return err
}
if intValue < 0 {
return fmt.Errorf("cpu must be positive")
}
return nil
}
func CompareInfraProviderResource(a, b InfraProviderResource) int {
// If either is invalid, return 0 since we cant compare them
err := validateInfraProviderResource(a)
if err != nil {
return 0
}
err = validateInfraProviderResource(b)
if err != nil {
return 0
}
cpuA, _ := strconv.Atoi(withoutSpace(*a.CPU))
cpuB, _ := strconv.Atoi(withoutSpace(*b.CPU))
if cpuA != cpuB {
return cpuA - cpuB
}
memoryA, _ := units.RAMInBytes(withoutSpace(*a.Memory))
memoryB, _ := units.RAMInBytes(withoutSpace(*b.Memory))
if memoryA != memoryB {
return int(memoryA - memoryB)
}
diskA, _ := units.RAMInBytes(withoutSpace(*a.Disk))
diskB, _ := units.RAMInBytes(withoutSpace(*b.Disk))
if diskA != diskB {
return int(diskA - diskB)
}
if a.Region != b.Region {
if a.Region < b.Region {
return -1
}
return 1
}
return 0
}
type InfraProviderTemplate struct {
ID int64 `json:"-"`
Identifier string `json:"identifier"`
InfraProviderConfigID int64 `json:"-"`
InfraProviderConfigIdentifier string `json:"config_identifier"`
Description string `json:"description"`
Data string `json:"data"`
Version int64 `json:"-"`
SpaceID int64 `json:"space_id"`
SpacePath string `json:"space_path"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
}
type InfraProviderConfigFilter struct {
SpaceIDs []int64
Type enum.InfraProviderType
ApplyResourcesACL bool
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/github_connector_data.go | types/github_connector_data.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"fmt"
"github.com/harness/gitness/types/enum"
)
type GithubConnectorData struct {
APIURL string `json:"api_url"`
Insecure bool `json:"insecure"`
Auth *ConnectorAuth `json:"auth"`
}
func (g *GithubConnectorData) Validate() error {
if g.Auth == nil {
return fmt.Errorf("auth is required for github connectors")
}
if g.Auth.AuthType != enum.ConnectorAuthTypeBearer {
return fmt.Errorf("only bearer token auth is supported for github connectors")
}
if err := g.Auth.Validate(); err != nil {
return fmt.Errorf("invalid auth credentials: %w", err)
}
return nil
}
func (g *GithubConnectorData) Type() enum.ConnectorType {
return enum.ConnectorTypeGithub
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/ai_agent_auth.go | types/ai_agent_auth.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import "github.com/harness/gitness/types/enum"
type AIAgentAuth struct {
AuthType enum.AIAgentAuth `json:"type"`
APIKey APIKey `json:"api_key,omitempty"`
}
type APIKey struct {
Value *MaskSecret `json:"value"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/resolved_feature.go | types/resolved_feature.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 types
import (
"fmt"
"sort"
"strconv"
"strings"
"github.com/Masterminds/semver/v3"
)
type ResolvedFeature struct {
ResolvedOptions map[string]string `json:"options,omitempty"`
OverriddenOptions map[string]any `json:"overridden_options,omitempty"`
Digest string `json:"string,omitempty"`
DownloadedFeature *DownloadedFeature `json:"downloaded_feature,omitempty"`
}
type DownloadedFeature struct {
FeatureFolderName string `json:"feature_folder_name,omitempty"`
Source string `json:"source,omitempty"`
SourceWithoutTag string `json:"source_without_tag,omitempty"`
Tag string `json:"tag,omitempty"`
CanonicalName string `json:"canonical_name,omitempty"`
DevcontainerFeatureConfig *DevcontainerFeatureConfig `json:"devcontainer_feature_config,omitempty"`
}
func (r *ResolvedFeature) Print() string {
options := make([]string, 0, len(r.ResolvedOptions))
for key, value := range r.ResolvedOptions {
options = append(options, fmt.Sprintf("%s=%s", key, value))
}
return fmt.Sprintf("%s %+v", r.DownloadedFeature.Source, options)
}
// CompareResolvedFeature implements the following comparison rules.
// 1. Compare and sort each Feature lexicographically by their fully qualified resource name
// (For OCI-published Features, that means the ID without version or digest.). If the comparison is equal:
// 2. Compare and sort each Feature from oldest to newest tag (latest being the “most new”). If the comparison is equal:
// 3. Compare and sort each Feature by their options by:
// 3.1 Greatest number of user-defined options (note omitting an option will default that value to the Feature’s
// default value and is not considered a user-defined option). If the comparison is equal:
// 3.2 Sort the provided option keys lexicographically. If the comparison is equal:
// 3.3 Sort the provided option values lexicographically. If the comparison is equal:
// 4. Sort Features by their canonical name (For OCI-published Features, the Feature ID resolved to the digest hash).
// 5. If there is no difference based on these comparator rules, the Features are considered equal.
// Reference: https://containers.dev/implementors/features/#definition-feature-equality (Round Stable Sort).
func CompareResolvedFeature(a, b *ResolvedFeature) int {
var comparison int
comparison = strings.Compare(a.DownloadedFeature.SourceWithoutTag, b.DownloadedFeature.SourceWithoutTag)
if comparison != 0 {
return comparison
}
comparison, _ = compareTags(a.DownloadedFeature.Tag, b.DownloadedFeature.Tag)
if comparison != 0 {
return comparison
}
comparison = compareOverriddenOptions(a.OverriddenOptions, b.OverriddenOptions)
if comparison != 0 {
return comparison
}
return strings.Compare(a.DownloadedFeature.CanonicalName, b.DownloadedFeature.CanonicalName)
}
func compareTags(a, b string) (int, error) {
if a == FeatureDefaultTag && b == FeatureDefaultTag {
return 0, nil
}
if a == FeatureDefaultTag {
return 1, nil
}
if b == FeatureDefaultTag {
return -1, nil
}
versionA, err := semver.NewVersion(a)
if err != nil {
return 0, err
}
versionB, err := semver.NewVersion(b)
if err != nil {
return 0, err
}
return versionA.Compare(versionB), nil
}
func compareOverriddenOptions(a, b map[string]any) int {
if len(a) != len(b) {
return len(a) - len(b)
}
keysA, valuesA := getSortedOptions(a)
keysB, valuesB := getSortedOptions(b)
for i := range keysA {
if keysA[i] == keysB[i] {
continue
}
return strings.Compare(keysA[i], keysB[i])
}
for i := range valuesA {
if valuesA[i] == valuesB[i] {
continue
}
return strings.Compare(valuesA[i], valuesB[i])
}
return 0
}
// getSortedOptions returns the keys and values of a map sorted lexicographically.
func getSortedOptions(m map[string]any) ([]string, []string) {
keys := make([]string, 0, len(m))
for key := range m {
keys = append(keys, key)
}
sort.Strings(keys)
values := make([]string, 0, len(m))
for _, key := range keys {
value := m[key]
switch v := value.(type) {
case string:
values = append(values, v)
case bool:
values = append(values, strconv.FormatBool(v))
}
}
return keys, values
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/webhook.go | types/webhook.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/json"
"slices"
"github.com/harness/gitness/types/enum"
)
// Webhook represents a webhook.
type Webhook struct {
// TODO [CODE-1364]: Hide once UID/Identifier migration is completed.
ID int64 `json:"id" yaml:"id"`
Version int64 `json:"version" yaml:"-"`
ParentID int64 `json:"parent_id" yaml:"-"`
ParentType enum.WebhookParent `json:"parent_type" yaml:"-"`
CreatedBy int64 `json:"created_by" yaml:"created_by"`
Created int64 `json:"created" yaml:"created"`
Updated int64 `json:"updated" yaml:"updated"`
Type enum.WebhookType `json:"-"`
// scope 0 indicates repo; scope > 0 indicates space depth level
Scope int64 `json:"scope"`
Identifier string `json:"identifier"`
// TODO [CODE-1364]: Remove once UID/Identifier migration is completed.
DisplayName string `json:"display_name" yaml:"display_name"`
Description string `json:"description" yaml:"description"`
URL string `json:"url" yaml:"url"`
Secret string `json:"-" yaml:"-"`
Enabled bool `json:"enabled" yaml:"enabled"`
Insecure bool `json:"insecure" yaml:"insecure"`
Triggers []enum.WebhookTrigger `json:"triggers" yaml:"triggers"`
LatestExecutionResult *enum.WebhookExecutionResult `json:"latest_execution_result,omitempty" yaml:"-"`
ExtraHeaders []ExtraHeader `json:"extra_headers,omitempty" yaml:"-"`
}
// MarshalJSON overrides the default json marshaling for `Webhook` allowing us to inject the `HasSecret` field.
// NOTE: This is required as we don't expose the `Secret` field and thus the caller wouldn't know whether
// the webhook contains a secret or not.
// NOTE: This is used as an alternative to adding an `HasSecret` field to Webhook itself, which would
// require us to keep `HasSecret` in sync with the `Secret` field, while `HasSecret` is not used internally at all.
func (w *Webhook) MarshalJSON() ([]byte, error) {
// WebhookAlias allows us to embed the original Webhook object (avoiding redefining all fields)
// while avoiding an infinite loop of marsheling.
type WebhookAlias Webhook
return json.Marshal(&struct {
*WebhookAlias
HasSecret bool `json:"has_secret"`
// TODO [CODE-1363]: remove after identifier migration.
UID string `json:"uid"`
}{
WebhookAlias: (*WebhookAlias)(w),
HasSecret: w != nil && w.Secret != "",
// TODO [CODE-1363]: remove after identifier migration.
UID: w.Identifier,
})
}
// Clone makes a deep copy of the webhook object.
func (w Webhook) Clone() Webhook {
webhook := w
// Deep copy the LatestExecutionResult pointer if it exists
if w.LatestExecutionResult != nil {
result := *w.LatestExecutionResult
webhook.LatestExecutionResult = &result
}
// Deep copy the Triggers slice
if len(w.Triggers) > 0 {
triggers := make([]enum.WebhookTrigger, len(w.Triggers))
copy(triggers, w.Triggers)
webhook.Triggers = triggers
}
// Deep copy the ExtraHeaders slice
webhook.ExtraHeaders = slices.Clone(w.ExtraHeaders)
return webhook
}
type WebhookCreateInput struct {
// TODO [CODE-1363]: remove after identifier migration.
UID string `json:"uid" deprecated:"true"`
Identifier string `json:"identifier"`
// TODO [CODE-1364]: Remove once UID/Identifier migration is completed.
DisplayName string `json:"display_name"`
Description string `json:"description"`
URL string `json:"url"`
Secret string `json:"secret"`
Enabled bool `json:"enabled"`
Insecure bool `json:"insecure"`
Triggers []enum.WebhookTrigger `json:"triggers"`
ExtraHeaders []ExtraHeader `json:"extra_headers,omitempty"`
}
type WebhookSignatureMetadata struct {
Signature string
BodyBytes []byte
}
type WebhookUpdateInput struct {
// TODO [CODE-1363]: remove after identifier migration.
UID *string `json:"uid" deprecated:"true"`
Identifier *string `json:"identifier"`
// TODO [CODE-1364]: Remove once UID/Identifier migration is completed.
DisplayName *string `json:"display_name"`
Description *string `json:"description"`
URL *string `json:"url"`
Secret *string `json:"secret"`
Enabled *bool `json:"enabled"`
Insecure *bool `json:"insecure"`
Triggers []enum.WebhookTrigger `json:"triggers"`
ExtraHeaders []ExtraHeader `json:"extra_headers,omitempty"`
}
// WebhookExecution represents a single execution of a webhook.
type WebhookExecution struct {
ID int64 `json:"id"`
RetriggerOf *int64 `json:"retrigger_of,omitempty"`
Retriggerable bool `json:"retriggerable"`
Created int64 `json:"created"`
WebhookID int64 `json:"webhook_id"`
TriggerType enum.WebhookTrigger `json:"trigger_type"`
TriggerID string `json:"-"`
Result enum.WebhookExecutionResult `json:"result"`
Duration int64 `json:"duration"`
Error string `json:"error,omitempty"`
Request WebhookExecutionRequest `json:"request"`
Response WebhookExecutionResponse `json:"response"`
}
// WebhookExecutionRequest represents the request of a webhook execution.
type WebhookExecutionRequest struct {
URL string `json:"url"`
Headers string `json:"headers"`
Body string `json:"body"`
}
// WebhookExecutionResponse represents the response of a webhook execution.
type WebhookExecutionResponse struct {
StatusCode int `json:"status_code"`
Status string `json:"status"`
Headers string `json:"headers"`
Body string `json:"body"`
}
// WebhookFilter stores Webhook query parameters for listing.
type WebhookFilter struct {
Query string `json:"query"`
Page int `json:"page"`
Size int `json:"size"`
Sort enum.WebhookAttr `json:"sort"`
Order enum.Order `json:"order"`
SkipInternal bool `json:"-"`
}
// WebhookExecutionFilter stores WebhookExecution query parameters for listing.
type WebhookExecutionFilter struct {
Page int `json:"page"`
Size int `json:"size"`
}
type WebhookParentInfo struct {
Type enum.WebhookParent
ID int64
}
// WebhookCore represents a webhook DTO object.
type WebhookCore struct {
ID int64
Version int64
ParentID int64
ParentType enum.WebhookParent
CreatedBy int64
Created int64
Updated int64
Type enum.WebhookType
Scope int64
Identifier string
DisplayName string
Description string
URL string
Secret string
Enabled bool
Insecure bool
Triggers []enum.WebhookTrigger
LatestExecutionResult *enum.WebhookExecutionResult
SecretIdentifier string
SecretSpaceID int64
ExtraHeaders []ExtraHeader
}
// WebhookExecutionCore represents a webhook execution DTO object.
type WebhookExecutionCore struct {
ID int64
RetriggerOf *int64
Retriggerable bool
Created int64
WebhookID int64
TriggerType enum.WebhookTrigger
TriggerID string
Result enum.WebhookExecutionResult
Duration int64
Error string
Request WebhookExecutionRequest
Response WebhookExecutionResponse
}
type ExtraHeader struct {
Key string `json:"key,omitempty"`
Value string `json:"value,omitempty"`
Masked bool `json:"masked,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/stream.go | types/stream.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
type Stream[T any] interface {
Next() (T, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/path.go | types/path.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import "encoding/json"
const (
PathSeparatorAsString = string(PathSeparator)
PathSeparator = '/'
)
// SpacePath represents a full path to a space.
type SpacePath struct {
Value string `json:"value"`
IsPrimary bool `json:"is_primary"`
SpaceID int64 `json:"space_id"`
}
// SpacePathSegment represents a segment of a path to a space.
type SpacePathSegment struct {
// TODO: int64 ID doesn't match DB
ID int64 `json:"-"`
Identifier string `json:"identifier"`
IsPrimary bool `json:"is_primary"`
SpaceID int64 `json:"space_id"`
ParentID int64 `json:"parent_id"`
CreatedBy int64 `json:"created_by"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
}
// TODO [CODE-1363]: remove after identifier migration.
func (s SpacePathSegment) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias SpacePathSegment
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(s),
UID: s.Identifier,
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/trigger.go | types/trigger.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 types
import (
"encoding/json"
"github.com/harness/gitness/types/enum"
)
type Trigger struct {
ID int64 `json:"-"`
Description string `json:"description"`
Type string `json:"trigger_type"`
PipelineID int64 `json:"pipeline_id"`
Secret string `json:"-"`
RepoID int64 `json:"repo_id"`
CreatedBy int64 `json:"created_by"`
Disabled bool `json:"disabled"`
Actions []enum.TriggerAction `json:"actions"`
Identifier string `json:"identifier"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
Version int64 `json:"-"`
}
// TODO [CODE-1363]: remove after identifier migration.
func (s Trigger) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias Trigger
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(s),
UID: s.Identifier,
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/githook.go | types/githook.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 types
import (
"github.com/harness/gitness/git/hook"
)
// GithookInputBase contains the base input of the githook apis.
type GithookInputBase struct {
RepoID int64
PrincipalID int64
Internal bool // Internal calls originate from Gitness, and external calls are direct git pushes.
}
// GithookPreReceiveInput is the input for the pre-receive githook api call.
type GithookPreReceiveInput struct {
GithookInputBase
hook.PreReceiveInput
}
// GithookUpdateInput is the input for the update githook api call.
type GithookUpdateInput struct {
GithookInputBase
hook.UpdateInput
}
// GithookPostReceiveInput is the input for the post-receive githook api call.
type GithookPostReceiveInput struct {
GithookInputBase
hook.PostReceiveInput
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/stage.go | types/stage.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 types
import "github.com/harness/gitness/types/enum"
type Stage struct {
ID int64 `json:"-"`
ExecutionID int64 `json:"execution_id"`
RepoID int64 `json:"repo_id"`
Number int64 `json:"number"`
Name string `json:"name"`
Kind string `json:"kind,omitempty"`
Type string `json:"type,omitempty"`
Status enum.CIStatus `json:"status"`
Error string `json:"error,omitempty"`
ErrIgnore bool `json:"errignore,omitempty"`
ExitCode int `json:"exit_code"`
Machine string `json:"machine,omitempty"`
OS string `json:"os,omitempty"`
Arch string `json:"arch,omitempty"`
Variant string `json:"variant,omitempty"`
Kernel string `json:"kernel,omitempty"`
Limit int `json:"limit,omitempty"`
LimitRepo int `json:"throttle,omitempty"`
Started int64 `json:"started,omitempty"`
Stopped int64 `json:"stopped,omitempty"`
Created int64 `json:"-"`
Updated int64 `json:"-"`
Version int64 `json:"-"`
OnSuccess bool `json:"on_success"`
OnFailure bool `json:"on_failure"`
DependsOn []string `json:"depends_on,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Steps []*Step `json:"steps,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/service.go | types/service.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package types defines common data structures.
package types
import "github.com/harness/gitness/types/enum"
type (
// Service is a principal representing a different internal service that runs alongside gitness.
Service struct {
// Fields from Principal
ID int64 `db:"principal_id" json:"id"`
UID string `db:"principal_uid" json:"uid"`
Email string `db:"principal_email" json:"email"`
DisplayName string `db:"principal_display_name" json:"display_name"`
Admin bool `db:"principal_admin" json:"admin"`
Blocked bool `db:"principal_blocked" json:"blocked"`
Salt string `db:"principal_salt" json:"-"`
Created int64 `db:"principal_created" json:"created"`
Updated int64 `db:"principal_updated" json:"updated"`
}
)
func (s *Service) ToPrincipal() *Principal {
return &Principal{
ID: s.ID,
UID: s.UID,
Email: s.Email,
Type: enum.PrincipalTypeService,
DisplayName: s.DisplayName,
Admin: s.Admin,
Blocked: s.Blocked,
Salt: s.Salt,
Created: s.Created,
Updated: s.Updated,
}
}
func (s *Service) ToPrincipalInfo() *PrincipalInfo {
return s.ToPrincipal().ToPrincipalInfo()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/image_data.go | types/image_data.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
type ImageData struct {
User string `json:"user,omitempty"`
Arch string `json:"arch,omitempty"`
OS string `json:"os,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/membership.go | types/membership.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"github.com/harness/gitness/types/enum"
)
// MembershipKey can be used as a key for finding a user's space membership info.
type MembershipKey struct {
SpaceID int64
PrincipalID int64
}
// Membership represents a user's membership of a space.
type Membership struct {
MembershipKey `json:"-"`
CreatedBy int64 `json:"-"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
Role enum.MembershipRole `json:"role"`
}
// MembershipUser adds user info to the Membership data.
type MembershipUser struct {
Membership
Principal PrincipalInfo `json:"principal"`
AddedBy PrincipalInfo `json:"added_by"`
}
// MembershipUserFilter holds membership user query parameters.
type MembershipUserFilter struct {
ListQueryFilter
Sort enum.MembershipUserSort `json:"sort"`
Order enum.Order `json:"order"`
}
// MembershipSpace adds space info to the Membership data.
type MembershipSpace struct {
Membership
Space Space `json:"space"`
AddedBy PrincipalInfo `json:"added_by"`
}
// MembershipSpaceFilter holds membership space query parameters.
type MembershipSpaceFilter struct {
ListQueryFilter
Sort enum.MembershipSpaceSort `json:"sort"`
Order enum.Order `json:"order"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/token.go | types/token.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/json"
"github.com/harness/gitness/types/enum"
)
// Represents server side infos stored for tokens we distribute.
type Token struct {
// TODO: int64 ID doesn't match DB
ID int64 `db:"token_id" json:"-"`
PrincipalID int64 `db:"token_principal_id" json:"principal_id"`
Type enum.TokenType `db:"token_type" json:"type"`
Identifier string `db:"token_uid" json:"identifier"`
// ExpiresAt is an optional unix time that if specified restricts the validity of a token.
ExpiresAt *int64 `db:"token_expires_at" json:"expires_at,omitempty"`
// IssuedAt is the unix time at which the token was issued.
IssuedAt int64 `db:"token_issued_at" json:"issued_at"`
CreatedBy int64 `db:"token_created_by" json:"created_by"`
}
// TODO [CODE-1363]: remove after identifier migration.
func (t Token) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias Token
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(t),
UID: t.Identifier,
})
}
// TokenResponse is returned as part of token creation for PAT / SAT / User Session.
type TokenResponse struct {
AccessToken string `json:"access_token"`
Token Token `json:"token"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/usage_metric.go | types/usage_metric.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 types
import "time"
type UsageMetric struct {
Date time.Time `json:"-"`
RootSpaceID int64 `json:"root_space_id"`
BandwidthOut int64 `json:"bandwidth_out"`
BandwidthIn int64 `json:"bandwidth_in"`
StorageTotal int64 `json:"storage_total"`
LFSStorageTotal int64 `json:"lfs_storage_total"`
Pushes int64 `json:"pushes"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/config.go | types/config.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 types
import (
"time"
"github.com/harness/gitness/blob"
"github.com/harness/gitness/events"
gitenum "github.com/harness/gitness/git/enum"
"github.com/harness/gitness/lock"
"github.com/harness/gitness/pubsub"
gossh "golang.org/x/crypto/ssh"
)
// Config stores the system configuration.
type Config struct {
// InstanceID specifis the ID of the Harness instance.
// NOTE: If the value is not provided the hostname of the machine is used.
InstanceID string `envconfig:"GITNESS_INSTANCE_ID"`
Debug bool `envconfig:"GITNESS_DEBUG"`
Trace bool `envconfig:"GITNESS_TRACE"`
// GracefulShutdownTime defines the max time we wait when shutting down a server.
// 5min should be enough for most git clones to complete.
GracefulShutdownTime time.Duration `envconfig:"GITNESS_GRACEFUL_SHUTDOWN_TIME" default:"300s"`
UserSignupEnabled bool `envconfig:"GITNESS_USER_SIGNUP_ENABLED" default:"true"`
NestedSpacesEnabled bool `envconfig:"GITNESS_NESTED_SPACES_ENABLED" default:"false"`
// PublicResourceCreationEnabled specifies whether a user can create publicly accessible resources.
PublicResourceCreationEnabled bool `envconfig:"GITNESS_PUBLIC_RESOURCE_CREATION_ENABLED" default:"true"`
Profiler struct {
Type string `envconfig:"GITNESS_PROFILER_TYPE"`
ServiceName string `envconfig:"GITNESS_PROFILER_SERVICE_NAME" default:"gitness"`
}
// URL defines the URLs via which the different parts of the service are reachable by.
URL struct {
// Base is used to generate external facing URLs in case they aren't provided explicitly.
// Value is derived from Server.HTTP Config unless explicitly specified (e.g. http://localhost:3000).
Base string `envconfig:"GITNESS_URL_BASE"`
// Git defines the external URL via which the GIT API is reachable.
// NOTE: for routing to work properly, the request path & hostname reaching gitness
// have to satisfy at least one of the following two conditions:
// - Path ends with `/git`
// - Hostname is different to API hostname
// (this could be after proxy path / header rewrite).
// Value is derived from Base unless explicitly specified (e.g. http://localhost:3000/git).
Git string `envconfig:"GITNESS_URL_GIT"`
// GitSSH defines the external URL via which the GIT SSH server is reachable.
// Value is derived from Base or SSH Config unless explicitly specified (e.g. ssh://localhost).
GitSSH string `envconfig:"GITNESS_URL_GIT_SSH"`
// API defines the external URL via which the rest API is reachable.
// NOTE: for routing to work properly, the request path reaching Harness has to end with `/api`
// (this could be after proxy path rewrite).
// Value is derived from Base unless explicitly specified (e.g. http://localhost:3000/api).
API string `envconfig:"GITNESS_URL_API"`
// UI defines the external URL via which the UI is reachable.
// Value is derived from Base unless explicitly specified (e.g. http://localhost:3000).
UI string `envconfig:"GITNESS_URL_UI"`
// Internal defines the internal URL via which the service is reachable.
// Value is derived from HTTP.Server unless explicitly specified (e.g. http://localhost:3000).
Internal string `envconfig:"GITNESS_URL_INTERNAL"`
// Container is the endpoint that can be used by running container builds to communicate
// with Harness (for example while performing a clone on a local repo).
// host.docker.internal allows a running container to talk to services exposed on the host
// (either running directly or via a port exposed in a docker container).
// Value is derived from HTTP.Server unless explicitly specified (e.g. http://host.docker.internal:3000).
Container string `envconfig:"GITNESS_URL_CONTAINER"`
// Registry is used as a base to generate external facing URLs.
// Value is derived from HTTP.Server unless explicitly specified (e.g. http://host.docker.internal:3000).
Registry string `envconfig:"GITNESS_URL_REGISTRY"`
}
// Git defines the git configuration parameters
Git struct {
// Trace specifies whether git operations should be traces.
// NOTE: Currently limited to 'push' operation until we move to internal command package.
Trace bool `envconfig:"GITNESS_GIT_TRACE"`
// DefaultBranch specifies the default branch for new repositories.
DefaultBranch string `envconfig:"GITNESS_GIT_DEFAULTBRANCH" default:"main"`
// Root specifies the directory containing git related data (e.g. repos, ...)
Root string `envconfig:"GITNESS_GIT_ROOT"`
// TmpDir (optional) specifies the directory for temporary data (e.g. repo clones, ...)
TmpDir string `envconfig:"GITNESS_GIT_TMP_DIR"`
// HookPath points to the binary used as git server hook.
HookPath string `envconfig:"GITNESS_GIT_HOOK_PATH"`
// LastCommitCache holds configuration options for the last commit cache.
LastCommitCache struct {
// Mode determines where the cache will be. Valid values are "inmemory" (default), "redis" or "none".
Mode gitenum.LastCommitCacheMode `envconfig:"GITNESS_GIT_LAST_COMMIT_CACHE_MODE" default:"inmemory"`
// Duration defines cache duration of last commit.
Duration time.Duration `envconfig:"GITNESS_GIT_LAST_COMMIT_CACHE_DURATION" default:"12h"`
}
}
// Encrypter defines the parameters for the encrypter
Encrypter struct {
Secret string `envconfig:"GITNESS_ENCRYPTER_SECRET"` // key used for encryption
MixedContent bool `envconfig:"GITNESS_ENCRYPTER_MIXED_CONTENT"`
}
// HTTP defines the http server configuration parameters
HTTP struct {
Port int `envconfig:"GITNESS_HTTP_PORT" default:"3000"`
Host string `envconfig:"GITNESS_HTTP_HOST"`
Proto string `envconfig:"GITNESS_HTTP_PROTO" default:"http"`
}
// Acme defines Acme configuration parameters.
Acme struct {
Enabled bool `envconfig:"GITNESS_ACME_ENABLED"`
Endpont string `envconfig:"GITNESS_ACME_ENDPOINT"`
Email bool `envconfig:"GITNESS_ACME_EMAIL"`
Host string `envconfig:"GITNESS_ACME_HOST"`
}
SSH struct {
Enable bool `envconfig:"GITNESS_SSH_ENABLE" default:"false"`
Host string `envconfig:"GITNESS_SSH_HOST"`
Port int `envconfig:"GITNESS_SSH_PORT" default:"3022"`
// DefaultUser holds value for generating urls {user}@host:path and force check
// no other user can authenticate unless it is empty then any username is allowed
DefaultUser string `envconfig:"GITNESS_SSH_DEFAULT_USER" default:"git"`
Ciphers []string `envconfig:"GITNESS_SSH_CIPHERS"`
KeyExchanges []string `envconfig:"GITNESS_SSH_KEY_EXCHANGES"`
MACs []string `envconfig:"GITNESS_SSH_MACS"`
ServerHostKeys []string `envconfig:"GITNESS_SSH_HOST_KEYS"`
TrustedUserCAKeys []string `envconfig:"GITNESS_SSH_TRUSTED_USER_CA_KEYS"`
TrustedUserCAKeysFile string `envconfig:"GITNESS_SSH_TRUSTED_USER_CA_KEYS_FILENAME"`
TrustedUserCAKeysParsed []gossh.PublicKey
KeepAliveInterval time.Duration `envconfig:"GITNESS_SSH_KEEP_ALIVE_INTERVAL" default:"5s"`
ServerKeyPath string `envconfig:"GITNESS_SSH_SERVER_KEY_PATH" default:"ssh/gitness.rsa"`
}
// CI defines configuration related to build executions.
CI struct {
ParallelWorkers int `envconfig:"GITNESS_CI_PARALLEL_WORKERS" default:"2"`
// PluginsZipURL is a pointer to a zip containing all the plugins schemas.
// This could be a local path or an external location.
//nolint:lll
PluginsZipURL string `envconfig:"GITNESS_CI_PLUGINS_ZIP_URL" default:"https://github.com/bradrydzewski/plugins/archive/refs/heads/master.zip"`
// ContainerNetworks is a list of networks that all containers created as part of CI
// should be attached to.
// This can be needed when we don't want to use host.docker.internal (eg when a service mesh
// or proxy is being used) and instead want all the containers to run on the same network as
// the Harness container so that they can interact via the container name.
// In that case, GITNESS_URL_CONTAINER should also be changed
// (eg to http://<gitness_container_name>:<port>).
ContainerNetworks []string `envconfig:"GITNESS_CI_CONTAINER_NETWORKS"`
}
// Database defines the database configuration parameters.
Database struct {
Driver string `envconfig:"GITNESS_DATABASE_DRIVER" default:"sqlite3"`
Datasource string `envconfig:"GITNESS_DATABASE_DATASOURCE" default:"database.sqlite3"`
}
// BlobStore defines the blob storage configuration parameters.
BlobStore struct {
// MaxFileSize defines the maximum size of files that can be uploaded (in bytes)
MaxFileSize int64 `envconfig:"GITNESS_BLOBSTORE_MAX_FILE_SIZE" default:"10485760"` // 10MB default
// Provider is a name of blob storage service like filesystem or gcs or cloudflare
Provider blob.Provider `envconfig:"GITNESS_BLOBSTORE_PROVIDER" default:"filesystem"`
// Bucket is a path to the directory where the files will be stored when using filesystem blob storage,
// in case of gcs provider this will be the actual bucket where the images are stored.
Bucket string `envconfig:"GITNESS_BLOBSTORE_BUCKET"`
// In case of GCS provider, this is expected to be the path to the service account key file.
KeyPath string `envconfig:"GITNESS_BLOBSTORE_KEY_PATH" default:""`
// Email ID of the google service account that needs to be impersonated
TargetPrincipal string `envconfig:"GITNESS_BLOBSTORE_TARGET_PRINCIPAL" default:""`
ImpersonationLifetime time.Duration `envconfig:"GITNESS_BLOBSTORE_IMPERSONATION_LIFETIME" default:"12h"`
}
// Token defines token configuration parameters.
Token struct {
CookieName string `envconfig:"GITNESS_TOKEN_COOKIE_NAME" default:"token"`
Expire time.Duration `envconfig:"GITNESS_TOKEN_EXPIRE" default:"720h"`
}
Logs struct {
// S3 provides optional storage option for logs.
S3 struct {
Bucket string `envconfig:"GITNESS_LOGS_S3_BUCKET"`
Prefix string `envconfig:"GITNESS_LOGS_S3_PREFIX"`
Endpoint string `envconfig:"GITNESS_LOGS_S3_ENDPOINT"`
PathStyle bool `envconfig:"GITNESS_LOGS_S3_PATH_STYLE"`
}
}
// Cors defines http cors parameters
Cors struct {
AllowedOrigins []string `envconfig:"GITNESS_CORS_ALLOWED_ORIGINS" default:"*"`
AllowedMethods []string `envconfig:"GITNESS_CORS_ALLOWED_METHODS" default:"GET,POST,PATCH,PUT,DELETE,OPTIONS"`
AllowedHeaders []string `envconfig:"GITNESS_CORS_ALLOWED_HEADERS" default:"Origin,Accept,Accept-Language,Authorization,Content-Type,Content-Language,X-Requested-With,X-Request-Id"` //nolint:lll // struct tags can't be multiline
ExposedHeaders []string `envconfig:"GITNESS_CORS_EXPOSED_HEADERS" default:"Link"`
AllowCredentials bool `envconfig:"GITNESS_CORS_ALLOW_CREDENTIALS" default:"true"`
MaxAge int `envconfig:"GITNESS_CORS_MAX_AGE" default:"300"`
}
// Secure defines http security parameters.
Secure struct {
AllowedHosts []string `envconfig:"GITNESS_HTTP_ALLOWED_HOSTS"`
HostsProxyHeaders []string `envconfig:"GITNESS_HTTP_PROXY_HEADERS"`
SSLRedirect bool `envconfig:"GITNESS_HTTP_SSL_REDIRECT"`
SSLTemporaryRedirect bool `envconfig:"GITNESS_HTTP_SSL_TEMPORARY_REDIRECT"`
SSLHost string `envconfig:"GITNESS_HTTP_SSL_HOST"`
SSLProxyHeaders map[string]string `envconfig:"GITNESS_HTTP_SSL_PROXY_HEADERS"`
STSSeconds int64 `envconfig:"GITNESS_HTTP_STS_SECONDS"`
STSIncludeSubdomains bool `envconfig:"GITNESS_HTTP_STS_INCLUDE_SUBDOMAINS"`
STSPreload bool `envconfig:"GITNESS_HTTP_STS_PRELOAD"`
ForceSTSHeader bool `envconfig:"GITNESS_HTTP_STS_FORCE_HEADER"`
BrowserXSSFilter bool `envconfig:"GITNESS_HTTP_BROWSER_XSS_FILTER" default:"true"`
FrameDeny bool `envconfig:"GITNESS_HTTP_FRAME_DENY" default:"true"`
ContentTypeNosniff bool `envconfig:"GITNESS_HTTP_CONTENT_TYPE_NO_SNIFF"`
ContentSecurityPolicy string `envconfig:"GITNESS_HTTP_CONTENT_SECURITY_POLICY"`
ReferrerPolicy string `envconfig:"GITNESS_HTTP_REFERRER_POLICY"`
}
Principal struct {
// System defines the principal information used to create the system service.
System struct {
UID string `envconfig:"GITNESS_PRINCIPAL_SYSTEM_UID" default:"gitness"`
DisplayName string `envconfig:"GITNESS_PRINCIPAL_SYSTEM_DISPLAY_NAME" default:"Gitness"`
Email string `envconfig:"GITNESS_PRINCIPAL_SYSTEM_EMAIL" default:"system@gitness.io"`
}
// Pipeline defines the principal information used to create the pipeline service.
Pipeline struct {
UID string `envconfig:"GITNESS_PRINCIPAL_PIPELINE_UID" default:"pipeline"`
DisplayName string `envconfig:"GITNESS_PRINCIPAL_PIPELINE_DISPLAY_NAME" default:"Gitness Pipeline"`
Email string `envconfig:"GITNESS_PRINCIPAL_PIPELINE_EMAIL" default:"pipeline@gitness.io"`
}
// Gitspace defines the principal information used to create the gitspace service.
Gitspace struct {
UID string `envconfig:"GITNESS_PRINCIPAL_GITSPACE_UID" default:"gitspace"`
DisplayName string `envconfig:"GITNESS_PRINCIPAL_GITSPACE_DISPLAY_NAME" default:"Gitness Gitspace"`
Email string `envconfig:"GITNESS_PRINCIPAL_GITSPACE_EMAIL" default:"gitspace@gitness.io"`
}
// Admin defines the principal information used to create the admin user.
// NOTE: The admin user is only auto-created in case a password and an email is provided.
Admin struct {
UID string `envconfig:"GITNESS_PRINCIPAL_ADMIN_UID" default:"admin"`
DisplayName string `envconfig:"GITNESS_PRINCIPAL_ADMIN_DISPLAY_NAME" default:"Administrator"`
Email string `envconfig:"GITNESS_PRINCIPAL_ADMIN_EMAIL"` // No default email
Password string `envconfig:"GITNESS_PRINCIPAL_ADMIN_PASSWORD"` // No default password
}
}
Redis struct {
Endpoint string `envconfig:"GITNESS_REDIS_ENDPOINT" default:"localhost:6379"`
MaxRetries int `envconfig:"GITNESS_REDIS_MAX_RETRIES" default:"3"`
MinIdleConnections int `envconfig:"GITNESS_REDIS_MIN_IDLE_CONNECTIONS" default:"0"`
Password string `envconfig:"GITNESS_REDIS_PASSWORD"`
SentinelMode bool `envconfig:"GITNESS_REDIS_USE_SENTINEL" default:"false"`
SentinelMaster string `envconfig:"GITNESS_REDIS_SENTINEL_MASTER"`
SentinelEndpoint string `envconfig:"GITNESS_REDIS_SENTINEL_ENDPOINT"`
}
Events struct {
Mode events.Mode `envconfig:"GITNESS_EVENTS_MODE" default:"inmemory"`
Namespace string `envconfig:"GITNESS_EVENTS_NAMESPACE" default:"gitness"`
MaxStreamLength int64 `envconfig:"GITNESS_EVENTS_MAX_STREAM_LENGTH" default:"10000"`
ApproxMaxStreamLength bool `envconfig:"GITNESS_EVENTS_APPROX_MAX_STREAM_LENGTH" default:"true"`
}
Lock struct {
// Provider is a name of distributed lock service like redis, memory, file etc...
Provider lock.Provider `envconfig:"GITNESS_LOCK_PROVIDER" default:"inmemory"`
Expiry time.Duration `envconfig:"GITNESS_LOCK_EXPIRE" default:"8s"`
Tries int `envconfig:"GITNESS_LOCK_TRIES" default:"8"`
RetryDelay time.Duration `envconfig:"GITNESS_LOCK_RETRY_DELAY" default:"250ms"`
DriftFactor float64 `envconfig:"GITNESS_LOCK_DRIFT_FACTOR" default:"0.01"`
TimeoutFactor float64 `envconfig:"GITNESS_LOCK_TIMEOUT_FACTOR" default:"0.25"`
// AppNamespace is just service app prefix to avoid conflicts on key definition
AppNamespace string `envconfig:"GITNESS_LOCK_APP_NAMESPACE" default:"gitness"`
// DefaultNamespace is when mutex doesn't specify custom namespace for their keys
DefaultNamespace string `envconfig:"GITNESS_LOCK_DEFAULT_NAMESPACE" default:"default"`
}
PubSub struct {
// Provider is a name of distributed lock service like redis, memory, file etc...
Provider pubsub.Provider `envconfig:"GITNESS_PUBSUB_PROVIDER" default:"inmemory"`
// AppNamespace is just service app prefix to avoid conflicts on channel definition
AppNamespace string `envconfig:"GITNESS_PUBSUB_APP_NAMESPACE" default:"gitness"`
// DefaultNamespace is custom namespace for their channels
DefaultNamespace string `envconfig:"GITNESS_PUBSUB_DEFAULT_NAMESPACE" default:"default"`
HealthInterval time.Duration `envconfig:"GITNESS_PUBSUB_HEALTH_INTERVAL" default:"3s"`
SendTimeout time.Duration `envconfig:"GITNESS_PUBSUB_SEND_TIMEOUT" default:"60s"`
ChannelSize int `envconfig:"GITNESS_PUBSUB_CHANNEL_SIZE" default:"100"`
}
BackgroundJobs struct {
// MaxRunning is maximum number of jobs that can be running at once.
MaxRunning int `envconfig:"GITNESS_JOBS_MAX_RUNNING" default:"10"`
// RetentionTime is the duration after which non-recurring,
// finished and failed jobs will be purged from the DB.
RetentionTime time.Duration `envconfig:"GITNESS_JOBS_RETENTION_TIME" default:"120h"` // 5 days
}
Webhook struct {
// UserAgentIdentity specifies the identity used for the user agent header
// IMPORTANT: do not include version.
UserAgentIdentity string `envconfig:"GITNESS_WEBHOOK_USER_AGENT_IDENTITY" default:"Gitness"`
// HeaderIdentity specifies the identity used for headers in webhook calls (e.g. X-Gitness-Trigger, ...).
// NOTE: If no value is provided, the UserAgentIdentity will be used.
HeaderIdentity string `envconfig:"GITNESS_WEBHOOK_HEADER_IDENTITY"`
Concurrency int `envconfig:"GITNESS_WEBHOOK_CONCURRENCY" default:"4"`
MaxRetries int `envconfig:"GITNESS_WEBHOOK_MAX_RETRIES" default:"3"`
AllowPrivateNetwork bool `envconfig:"GITNESS_WEBHOOK_ALLOW_PRIVATE_NETWORK" default:"false"`
AllowLoopback bool `envconfig:"GITNESS_WEBHOOK_ALLOW_LOOPBACK" default:"false"`
// RetentionTime is the duration after which webhook executions will be purged from the DB.
RetentionTime time.Duration `envconfig:"GITNESS_WEBHOOK_RETENTION_TIME" default:"168h"` // 7 days
InternalSecret string `envconfig:"GITNESS_WEBHOOK_INTERNAL_SECRET"`
}
Trigger struct {
Concurrency int `envconfig:"GITNESS_TRIGGER_CONCURRENCY" default:"4"`
MaxRetries int `envconfig:"GITNESS_TRIGGER_MAX_RETRIES" default:"3"`
}
Branch struct {
Concurrency int `envconfig:"GITNESS_BRANCH_CONCURRENCY" default:"4"`
MaxRetries int `envconfig:"GITNESS_BRANCH_MAX_RETRIES" default:"3"`
}
Metric struct {
Enabled bool `envconfig:"GITNESS_METRIC_ENABLED" default:"true"`
Endpoint string `envconfig:"GITNESS_METRIC_ENDPOINT" default:"https://stats.drone.ci/api/v1/gitness"`
Token string `envconfig:"GITNESS_METRIC_TOKEN"`
// PostHogEndpoint is URL to the PostHog service
PostHogEndpoint string `envconfig:"GITNESS_METRIC_POSTHOG_ENDPOINT" default:"https://us.i.posthog.com"`
// PostHogProjectAPIKey (starts with "phc_") is public (can be exposed in frontend) token used to submit events.
PostHogProjectAPIKey string `envconfig:"GITNESS_METRIC_POSTHOG_PROJECT_APIKEY"`
// PostHogPersonalAPIKey (starts with "phx_") is sensitive. It's used to access private access points.
// It's not required for submitting events.
PostHogPersonalAPIKey string `envconfig:"GITNESS_METRIC_POSTHOG_PERSONAL_APIKEY"`
}
RepoSize struct {
Enabled bool `envconfig:"GITNESS_REPO_SIZE_ENABLED" default:"true"`
CRON string `envconfig:"GITNESS_REPO_SIZE_CRON" default:"0 0 * * *"`
MaxDuration time.Duration `envconfig:"GITNESS_REPO_SIZE_MAX_DURATION" default:"15m"`
NumWorkers int `envconfig:"GITNESS_REPO_SIZE_NUM_WORKERS" default:"5"`
}
Githook struct {
DisableAuth bool `envconfig:"GITNESS_GITHOOK_DISABLE_AUTH" default:"false"`
}
CodeOwners struct {
FilePaths []string `envconfig:"GITNESS_CODEOWNERS_FILEPATH" default:"CODEOWNERS,.harness/CODEOWNERS"`
}
SMTP struct {
Host string `envconfig:"GITNESS_SMTP_HOST"`
Port int `envconfig:"GITNESS_SMTP_PORT"`
Username string `envconfig:"GITNESS_SMTP_USERNAME"`
Password string `envconfig:"GITNESS_SMTP_PASSWORD"`
FromMail string `envconfig:"GITNESS_SMTP_FROM_MAIL"`
Insecure bool `envconfig:"GITNESS_SMTP_INSECURE"`
}
Notification struct {
MaxRetries int `envconfig:"GITNESS_NOTIFICATION_MAX_RETRIES" default:"3"`
Concurrency int `envconfig:"GITNESS_NOTIFICATION_CONCURRENCY" default:"4"`
}
KeywordSearch struct {
Concurrency int `envconfig:"GITNESS_KEYWORD_SEARCH_CONCURRENCY" default:"4"`
MaxRetries int `envconfig:"GITNESS_KEYWORD_SEARCH_MAX_RETRIES" default:"3"`
}
Repos struct {
// DeletedRetentionTime is the duration after which deleted repositories will be purged.
DeletedRetentionTime time.Duration `envconfig:"GITNESS_REPOS_DELETED_RETENTION_TIME" default:"2160h"` // 90 days
}
Docker struct {
// Host sets the url to the docker server.
Host string `envconfig:"GITNESS_DOCKER_HOST"`
// APIVersion sets the version of the API to reach, leave empty for latest.
APIVersion string `envconfig:"GITNESS_DOCKER_API_VERSION"`
// CertPath sets the path to load the TLS certificates from.
CertPath string `envconfig:"GITNESS_DOCKER_CERT_PATH"`
// TLSVerify enables or disables TLS verification, off by default.
TLSVerify string `envconfig:"GITNESS_DOCKER_TLS_VERIFY"`
// MachineHostName is the public host name of the machine on which the Docker.Host is running.
// If not set, it parses the host from the URL.Base (e.g. localhost from http://localhost:3000).
MachineHostName string `envconfig:"GITNESS_DOCKER_MACHINE_HOST_NAME"`
}
IDE struct {
VSCodeWeb struct {
// Port is the port on which the VSCode Web will be accessible.
Port int `envconfig:"GITNESS_IDE_VSCODEWEB_PORT" default:"8089"`
}
VSCode struct {
// Port is the port on which the SSH server for VSCode will be accessible.
Port int `envconfig:"GITNESS_IDE_VSCODE_PORT" default:"8088"`
PluginName string `envconfig:"GITNESS_IDE_VSCODE_Plugin_Name" default:"harness-inc.oss-gitspaces"`
}
Cursor struct {
// Port is the port on which the SSH server for Cursor will be accessible.
Port int `envconfig:"GITNESS_IDE_CURSOR_PORT" default:"8098"`
}
Windsurf struct {
// Port is the port on which the SSH server for Windsurf will be accessible.
Port int `envconfig:"GITNESS_IDE_WINDSURF_PORT" default:"8099"`
}
Intellij struct {
// Port is the port on which the SSH server for IntelliJ will be accessible
Port int `envconfig:"CDE_MANAGER_GITSPACE_IDE_INTELLIJ_PORT" default:"8090"`
}
Goland struct {
// Port is the port on which the SSH server for Goland will be accessible
Port int `envconfig:"CDE_MANAGER_GITSPACE_IDE_GOLAND_PORT" default:"8091"`
}
PyCharm struct {
// Port is the port on which the SSH server for PyCharm will be accessible
Port int `envconfig:"CDE_MANAGER_GITSPACE_IDE_PYCHARM_PORT" default:"8092"`
}
WebStorm struct {
// Port is the port on which the SSH server for WebStorm will be accessible
Port int `envconfig:"CDE_MANAGER_GITSPACE_IDE_WEBSTORM_PORT" default:"8093"`
}
CLion struct {
// Port is the port on which the SSH server for CLion will be accessible
Port int `envconfig:"CDE_MANAGER_GITSPACE_IDE_CLION_PORT" default:"8094"`
}
PHPStorm struct {
// Port is the port on which the SSH server for PHPStorm will be accessible
Port int `envconfig:"CDE_MANAGER_GITSPACE_IDE_PHPSTORM_PORT" default:"8095"`
}
RubyMine struct {
// Port is the port on which the SSH server for RubyMine will be accessible
Port int `envconfig:"CDE_MANAGER_GITSPACE_IDE_RUBYMINE_PORT" default:"8096"`
}
Rider struct {
// Port is the port on which the SSH server for Rider will be accessible
Port int `envconfig:"CDE_MANAGER_GITSPACE_IDE_RIDER_PORT" default:"8097"`
}
}
Gitspace struct {
// DefaultBaseImage is used to create the Gitspace when no devcontainer.json is absent or doesn't have image.
DefaultBaseImage string `envconfig:"GITNESS_GITSPACE_DEFAULT_BASE_IMAGE" default:"mcr.microsoft.com/devcontainers/base:dev-ubuntu-24.04"` //nolint:lll
Enable bool `envconfig:"GITNESS_GITSPACE_ENABLE" default:"false"`
AgentPort int `envconfig:"GITNESS_GITSPACE_AGENT_PORT" default:"8083"`
InfraTimeoutInMins int `envconfig:"GITNESS_INFRA_TIMEOUT_IN_MINS" default:"60"`
BusyActionInMins int `envconfig:"GITNESS_BUSY_ACTION_IN_MINS" default:"15"`
Events struct {
Concurrency int `envconfig:"GITNESS_GITSPACE_EVENTS_CONCURRENCY" default:"4"`
MaxRetries int `envconfig:"GITNESS_GITSPACE_EVENTS_MAX_RETRIES" default:"3"`
TimeoutInMins int `envconfig:"GITNESS_GITSPACE_EVENTS_TIMEOUT_IN_MINS" default:"45"`
}
}
UI struct {
ShowPlugin bool `envconfig:"GITNESS_UI_SHOW_PLUGIN" default:"false"`
}
Registry struct {
Enable bool `envconfig:"GITNESS_REGISTRY_ENABLED" default:"true"`
Storage struct {
// StorageType defines the type of storage to use for the registry. Options are: `filesystem`, `s3aws`
StorageType string `envconfig:"GITNESS_REGISTRY_STORAGE_TYPE" default:"filesystem"`
// FileSystemStorage defines the configuration for the filesystem storage if StorageType is `filesystem`.
FileSystemStorage struct {
MaxThreads int `envconfig:"GITNESS_REGISTRY_FILESYSTEM_MAX_THREADS" default:"100"`
RootDirectory string `envconfig:"GITNESS_REGISTRY_FILESYSTEM_ROOT_DIRECTORY"`
}
// S3Storage defines the configuration for the S3 storage if StorageType is `s3aws`.
S3Storage struct {
AccessKey string `envconfig:"GITNESS_REGISTRY_S3_ACCESS_KEY"`
SecretKey string `envconfig:"GITNESS_REGISTRY_S3_SECRET_KEY"`
Region string `envconfig:"GITNESS_REGISTRY_S3_REGION"`
RegionEndpoint string `envconfig:"GITNESS_REGISTRY_S3_REGION_ENDPOINT"`
ForcePathStyle bool `envconfig:"GITNESS_REGISTRY_S3_FORCE_PATH_STYLE" default:"true"`
Accelerate bool `envconfig:"GITNESS_REGISTRY_S3_ACCELERATED" default:"false"`
Bucket string `envconfig:"GITNESS_REGISTRY_S3_BUCKET"`
Encrypt bool `envconfig:"GITNESS_REGISTRY_S3_ENCRYPT" default:"false"`
KeyID string `envconfig:"GITNESS_REGISTRY_S3_KEY_ID"`
Secure bool `envconfig:"GITNESS_REGISTRY_S3_SECURE" default:"true"`
V4Auth bool `envconfig:"GITNESS_REGISTRY_S3_V4_AUTH" default:"true"`
ChunkSize int `envconfig:"GITNESS_REGISTRY_S3_CHUNK_SIZE" default:"10485760"`
MultipartCopyChunkSize int `envconfig:"GITNESS_REGISTRY_S3_MULTIPART_COPY_CHUNK_SIZE" default:"33554432"`
MultipartCopyMaxConcurrency int `envconfig:"GITNESS_REGISTRY_S3_MULTIPART_COPY_MAX_CONCURRENCY" default:"100"`
MultipartCopyThresholdSize int `envconfig:"GITNESS_REGISTRY_S3_MULTIPART_COPY_THRESHOLD_SIZE" default:"33554432"` //nolint:lll
RootDirectory string `envconfig:"GITNESS_REGISTRY_S3_ROOT_DIRECTORY"`
UseDualStack bool `envconfig:"GITNESS_REGISTRY_S3_USE_DUAL_STACK" default:"false"`
LogLevel string `envconfig:"GITNESS_REGISTRY_S3_LOG_LEVEL" default:"info"`
Delete bool `envconfig:"GITNESS_REGISTRY_S3_DELETE_ENABLED" default:"true"`
Redirect bool `envconfig:"GITNESS_REGISTRY_S3_STORAGE_REDIRECT" default:"false"`
Provider string `envconfig:"GITNESS_REGISTRY_S3_PROVIDER" default:"cloudflare"`
}
}
HTTP struct {
// GITNESS_REGISTRY_HTTP_SECRET is used to encrypt the upload session details during docker push.
// If not provided, a random secret will be generated. This may cause problems with uploads if multiple
// registries are behind a load-balancer
Secret string `envconfig:"GITNESS_REGISTRY_HTTP_SECRET"`
RelativeURL bool `envconfig:"GITNESS_OCI_RELATIVE_URL" default:"false"`
}
//nolint:lll
GarbageCollection struct {
Enabled bool `envconfig:"GITNESS_REGISTRY_GARBAGE_COLLECTION_ENABLED" default:"false"`
NoIdleBackoff bool `envconfig:"GITNESS_REGISTRY_GARBAGE_COLLECTION_NO_IDLE_BACKOFF" default:"false"`
MaxBackoffDuration time.Duration `envconfig:"GITNESS_REGISTRY_GARBAGE_COLLECTION_MAX_BACKOFF_DURATION" default:"10m"`
InitialIntervalDuration time.Duration `envconfig:"GITNESS_REGISTRY_GARBAGE_COLLECTION_INITIAL_INTERVAL_DURATION" default:"5s"` //nolint:lll
TransactionTimeoutDuration time.Duration `envconfig:"GITNESS_REGISTRY_GARBAGE_COLLECTION_TRANSACTION_TIMEOUT_DURATION" default:"10s"` //nolint:lll
BlobsStorageTimeoutDuration time.Duration `envconfig:"GITNESS_REGISTRY_GARBAGE_COLLECTION_BLOB_STORAGE_TIMEOUT_DURATION" default:"5s"` //nolint:lll
}
SetupDetailsAuthHeaderPrefix string `envconfig:"SETUP_DETAILS_AUTH_PREFIX" default:"Authorization: Bearer"`
PostProcessing struct {
Concurrency int `envconfig:"GITNESS_REGISTRY_POST_PROCESSING_CONCURRENCY" default:"4"`
MaxRetries int `envconfig:"GITNESS_REGISTRY_POST_PROCESSING_MAX_RETRIES" default:"3"`
AllowLoopback bool `envconfig:"GITNESS_REGISTRY_POST_PROCESSING_ALLOW_LOOPBACK" default:"false"`
}
}
Auth struct {
AnonymousUserSecret string `envconfig:"GITNESS_ANONYMOUS_USER_SECRET"`
}
Instrumentation struct {
Enable bool `envconfig:"GITNESS_INSTRUMENTATION_ENABLE" default:"false"`
Cron string `envconfig:"GITNESS_INSTRUMENTATION_CRON" default:"0 0 * * *"`
}
UsageMetrics struct {
Enabled bool `envconfig:"GITNESS_USAGE_METRICS_ENABLED" default:"false"`
MaxWorkers int `envconfig:"GITNESS_USAGE_METRICS_MAX_WORKERS" default:"5"`
}
Development struct {
UISourceOverride string `envconfig:"GITNESS_DEVELOPMENT_UI_SOURCE_OVERRIDE"`
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/devcontainer_config_customizations.go | types/devcontainer_config_customizations.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 types
import (
"encoding/json"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
const (
GitspaceCustomizationsKey CustomizationsKey = "harnessGitspaces"
VSCodeCustomizationsKey CustomizationsKey = "vscode"
JetBrainsCustomizationsKey CustomizationsKey = "jetbrains"
)
type CustomizationsKey string
func (ck CustomizationsKey) String() string {
return string(ck)
}
// DevContainerConfigCustomizations implements various Extract* function to extract out custom field defines in
// customization field in devcontainer.json.
type DevContainerConfigCustomizations map[string]any
// VSCodeCustomizationSpecs contains details about vscode customization.
// eg:
//
// "customizations": {
// // Configure properties specific to VS Code.
// "vscode": {
// "settings": {
// "java.home": "/docker-java-home"
// },
// "extensions": [
// "streetsidesoftware.code-spell-checker"
// ]
// }
// }
type VSCodeCustomizationSpecs struct {
Extensions []string `json:"extensions"`
Settings map[string]any `json:"settings"`
}
// GitspaceCustomizationSpecs contains details about harness platform connectors and AI agent configuration.
// eg:
//
// "customizations": {
// "harnessGitspaces": {
// "connectors": [
// {
// "type": "DockerRegistry",
// "identifier": "testharnessjfrog"
// },
// {
// "type": "Artifactory",
// "identifier": "testartifactoryconnector"
// }
// ],
// "ai-agent": {
// "type": "claude-code",
// "auth": "API-Key",
// "secret-ref": "secretref"
// }
// }
// }
type GitspaceCustomizationSpecs struct {
Connectors []struct {
Type string `json:"type"`
ID string `json:"identifier"`
} `json:"connectors"`
AIAgent *struct {
Type string `json:"type"`
Auth string `json:"auth"`
SecretRef string `json:"secret_ref"`
} `json:"ai_agent,omitempty"`
}
type JetBrainsBackend string
func (jb JetBrainsBackend) String() string {
return string(jb)
}
func (jb JetBrainsBackend) Valid() bool {
_, valid := ValidJetBrainsBackendSet[jb]
return valid
}
func (jb JetBrainsBackend) IdeType() enum.IDEType {
var ideType enum.IDEType
switch jb {
case IntelliJJetBrainsBackend:
ideType = enum.IDETypeIntelliJ
case GolandJetBrainsBackend:
ideType = enum.IDETypeGoland
case PyCharmJetBrainsBackend:
ideType = enum.IDETypePyCharm
case WebStormJetBrainsBackend:
ideType = enum.IDETypeWebStorm
case CLionJetBrainsBackend:
ideType = enum.IDETypeCLion
case PhpStormJetBrainsBackend:
ideType = enum.IDETypePHPStorm
case RubyMineJetBrainsBackend:
ideType = enum.IDETypeRubyMine
case RiderJetBrainsBackend:
ideType = enum.IDETypeRider
}
return ideType
}
const (
IntelliJJetBrainsBackend JetBrainsBackend = "IntelliJ"
GolandJetBrainsBackend JetBrainsBackend = "Goland"
PyCharmJetBrainsBackend JetBrainsBackend = "PyCharm"
WebStormJetBrainsBackend JetBrainsBackend = "WebStorm"
CLionJetBrainsBackend JetBrainsBackend = "CLion"
PhpStormJetBrainsBackend JetBrainsBackend = "PhpStorm"
RubyMineJetBrainsBackend JetBrainsBackend = "RubyMine"
RiderJetBrainsBackend JetBrainsBackend = "Rider"
)
var ValidJetBrainsBackendSet = map[JetBrainsBackend]struct{}{
IntelliJJetBrainsBackend: {},
GolandJetBrainsBackend: {},
PyCharmJetBrainsBackend: {},
WebStormJetBrainsBackend: {},
CLionJetBrainsBackend: {},
PhpStormJetBrainsBackend: {},
RubyMineJetBrainsBackend: {},
RiderJetBrainsBackend: {},
}
type JetBrainsCustomizationSpecs struct {
Backend JetBrainsBackend `json:"backend"`
Plugins []string `json:"plugins"`
}
func (dcc DevContainerConfigCustomizations) ExtractGitspaceSpec() *GitspaceCustomizationSpecs {
val, ok := dcc[GitspaceCustomizationsKey.String()]
if !ok {
return nil
}
// val has underlying map[string]interface{} type as it is default for JSON objects
// converting to json so that val can be marshaled to GitspaceCustomizationSpecs type.
rawData, _ := json.Marshal(&val)
var gitspaceSpecs GitspaceCustomizationSpecs
if err := json.Unmarshal(rawData, &gitspaceSpecs); err != nil {
return nil
}
return &gitspaceSpecs
}
func (dcc DevContainerConfigCustomizations) ExtractVSCodeSpec() *VSCodeCustomizationSpecs {
val, ok := dcc[VSCodeCustomizationsKey.String()]
if !ok {
// Log that the key is missing, but return nil
log.Warn().Msgf("VSCode customization key %q not found, returning empty struct",
VSCodeCustomizationsKey.String())
return nil
}
data, ok := val.(map[string]any)
if !ok {
// Log the type mismatch and return nil
log.Warn().Msgf("Unexpected data type for key %q, expected map[string]interface{}, but got %T",
VSCodeCustomizationsKey.String(), val)
return nil
}
rawData, err := json.Marshal(data)
if err != nil {
// Log the error during marshalling and return nil
log.Printf("Failed to marshal data for key %q: %v", VSCodeCustomizationsKey.String(), err)
return nil
}
var vsCodeCustomizationSpecs VSCodeCustomizationSpecs
if err := json.Unmarshal(rawData, &vsCodeCustomizationSpecs); err != nil {
// Log the error during unmarshalling and return nil
log.Printf("Failed to unmarshal data for key %q: %v", VSCodeCustomizationsKey.String(), err)
return nil
}
return &vsCodeCustomizationSpecs
}
func (dcc DevContainerConfigCustomizations) ExtractJetBrainsSpecs() *JetBrainsCustomizationSpecs {
data, ok := dcc[JetBrainsCustomizationsKey.String()]
if !ok {
// Log that the key is missing, but return nil
log.Warn().Msgf("JetBrains customization key %q not found, returning empty struct",
JetBrainsCustomizationsKey)
return nil
}
rawData, err := json.Marshal(data)
if err != nil {
// Log the error during marshalling and return nil
log.Printf("Failed to marshal data for key %q: %v", JetBrainsCustomizationsKey, err)
return nil
}
var jetbrainsSpecs JetBrainsCustomizationSpecs
if err := json.Unmarshal(rawData, &jetbrainsSpecs); err != nil {
// Log the error during unmarshalling and return nil
log.Printf("Failed to unmarshal data for key %q: %v", JetBrainsCustomizationsKey, err)
return nil
}
return &jetbrainsSpecs
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/fork.go | types/fork.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 types
import "github.com/harness/gitness/git/sha"
type ForkSyncOutput struct {
AlreadyAncestor bool `json:"already_ancestor,omitempty"`
NewCommitSHA sha.SHA `json:"new_commit_sha,omitzero"`
ConflictFiles []string `json:"conflict_files,omitempty"`
Message string `json:"message,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/codeowners.go | types/codeowners.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 types
import (
"fmt"
"github.com/harness/gitness/types/enum"
)
type CodeOwnerEvaluation struct {
EvaluationEntries []CodeOwnerEvaluationEntry `json:"evaluation_entries"`
FileSha string `json:"file_sha"`
}
type CodeOwnerEvaluationEntry struct {
LineNumber int64 `json:"line_number"`
Pattern string `json:"pattern"`
OwnerEvaluations []OwnerEvaluation `json:"owner_evaluations"`
UserGroupOwnerEvaluations []UserGroupOwnerEvaluation `json:"user_group_owner_evaluations"`
}
type UserGroupOwnerEvaluation struct {
ID string `json:"id"`
Name string `json:"name"`
Evaluations []OwnerEvaluation `json:"evaluations"`
}
type OwnerEvaluation struct {
Owner PrincipalInfo `json:"owner"`
ReviewDecision enum.PullReqReviewDecision `json:"review_decision"`
ReviewSHA string `json:"review_sha"`
}
type CodeOwnersValidation struct {
Violations []CodeOwnersViolation `json:"violations"`
}
type CodeOwnersViolation struct {
Code enum.CodeOwnerViolationCode `json:"code"`
Message string `json:"message"`
Params []any `json:"params"`
}
func (violations *CodeOwnersValidation) Add(code enum.CodeOwnerViolationCode, message string) {
violations.Violations = append(violations.Violations, CodeOwnersViolation{
Code: code,
Message: message,
Params: nil,
})
}
func (violations *CodeOwnersValidation) Addf(code enum.CodeOwnerViolationCode, format string, params ...any) {
violations.Violations = append(violations.Violations, CodeOwnersViolation{
Code: code,
Message: fmt.Sprintf(format, params...),
Params: params,
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/PackageTag.go | types/PackageTag.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 types
type PackageTag struct {
PackageID int64
Tag string
ImageID int64
ArtifactID int64
CreatedAt int64
CreatedBy int64
UpdatedAt int64
UpdatedBy int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/gitspace_error.go | types/gitspace_error.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
// GitspaceError wraps any error and provides a user-friendly error message which can be relayed back to UI.
type GitspaceError struct {
Error error
ErrorMessage *string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/execution.go | types/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 types
import "github.com/harness/gitness/types/enum"
// ExecutionFilter stores execution query parameters.
type ListExecutionsFilter struct {
ListQueryFilter
PipelineIdentifier string `json:"pipeline_identifier"`
Sort enum.ExecutionSort `json:"sort"`
Order enum.Order `json:"order"`
}
// Execution represents an instance of a pipeline execution.
type Execution struct {
ID int64 `json:"-"`
PipelineID int64 `json:"pipeline_id"`
CreatedBy int64 `json:"created_by"`
RepoID int64 `json:"repo_id"`
Trigger string `json:"trigger,omitempty"`
Number int64 `json:"number"`
Parent int64 `json:"parent,omitempty"`
Status enum.CIStatus `json:"status"`
Error string `json:"error,omitempty"`
Event enum.TriggerEvent `json:"event,omitempty"`
Action enum.TriggerAction `json:"action,omitempty"`
Link string `json:"link,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
Title string `json:"title,omitempty"`
Message string `json:"message,omitempty"`
Before string `json:"before,omitempty"`
After string `json:"after,omitempty"`
Ref string `json:"ref,omitempty"`
Fork string `json:"source_repo,omitempty"`
Source string `json:"source,omitempty"`
Target string `json:"target,omitempty"`
Author string `json:"author_login,omitempty"`
AuthorName string `json:"author_name,omitempty"`
AuthorEmail string `json:"author_email,omitempty"`
AuthorAvatar string `json:"author_avatar,omitempty"`
Sender string `json:"sender,omitempty"`
Params map[string]string `json:"params,omitempty"`
Cron string `json:"cron,omitempty"`
Deploy string `json:"deploy_to,omitempty"`
DeployID int64 `json:"deploy_id,omitempty"`
Debug bool `json:"debug,omitempty"`
Started int64 `json:"started,omitempty"`
Finished int64 `json:"finished,omitempty"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
Version int64 `json:"-"`
Stages []*Stage `json:"stages,omitempty"`
// Pipeline specific information not stored with executions
PipelineUID string `json:"pipeline_uid,omitempty"`
// Repo specific information not stored with executions
RepoUID string `json:"repo_uid,omitempty"`
}
type ExecutionInfo struct {
Number int64 `db:"execution_number" json:"number"`
PipelineID int64 `db:"execution_pipeline_id" json:"pipeline_id"`
Status enum.CIStatus `db:"execution_status" json:"status"`
CreatedBy int64 `db:"execution_created_by" json:"created_by"`
Trigger string `db:"execution_trigger" json:"trigger,omitempty"`
Event enum.TriggerEvent `db:"execution_event" json:"event,omitempty"`
Started int64 `db:"execution_started" json:"started,omitempty"`
Finished int64 `db:"execution_finished" json:"finished,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/infrastructure.go | types/infrastructure.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 types
import "github.com/harness/gitness/types/enum"
type InfraProviderParameterSchema struct {
Name string
Description string
DefaultValue string
Required bool
Secret bool
Editable bool
}
type InfraProviderParameter struct {
Name string
Value string
}
type PortMapping struct {
// PublishedPort is the port on which the container will be listening.
PublishedPort int
// ForwardedPort is the port on the infra to which the PublishedPort is forwarded.
ForwardedPort int
}
type InstanceInfo struct {
ID string `json:"id"`
Name string `json:"name"`
IPAddress string `json:"ip_address"`
Port int64 `json:"port"`
OS string `json:"os"`
Arch string `json:"arch"`
Provider string `json:"provider"`
PoolName string `json:"pool_name"`
Zone string `json:"zone"`
StorageIdentifier string `json:"storage_identifier"`
CAKey []byte `json:"ca_key"`
CACert []byte `json:"ca_cert"`
TLSKey []byte `json:"tls_key"`
TLSCert []byte `json:"tls_cert"`
}
type Infrastructure struct {
// Identifier identifies the provisioned infra.
Identifier string
// SpaceID for the resource key.
SpaceID int64
// SpacePath for the resource key.
SpacePath string
// GitspaceConfigIdentifier is the gitspace config for which the infra is provisioned.
GitspaceConfigIdentifier string
// GitspaceInstanceIdentifier is the gitspace instance for which the infra is provisioned.
GitspaceInstanceIdentifier string
// GitspaceInstanceID is the gitspace instance id for which the infra is provisioned.
GitspaceInstanceID int64
// ProviderType specifies the type of the infra provider.
ProviderType enum.InfraProviderType
// InputParameters which are required by the provider to provision the infra.
InputParameters []InfraProviderParameter
// ConfigMetadata contains the infra config metadata required by the infra provider to provision the infra.
ConfigMetadata map[string]any
// Status of the infra.
Status enum.InfraStatus
// AgentHost through which the infra can be accessed.
AgentHost string
// AgentPort on which the agent can be accessed to orchestrate containers.
AgentPort int
// ProxyAgentHost on which to connect to agent incase a proxy is used.
ProxyAgentHost string
ProxyAgentPort int
// HostScheme is scheme to connect to the host e.g. https
HostScheme string
// GitspaceHost on which gitspace is accessible directly, without proxy being configured.
GitspaceHost string
// ProxyGitspaceHost on which gitspace is accessible through a proxy.
ProxyGitspaceHost string
GitspaceScheme string
// Storage is the name of the volume or disk created for the resource.
Storage string
// GitspacePortMappings contains the ports assigned for every requested port.
GitspacePortMappings map[int]*PortMapping
// VM Instance information from the init task
// that are required for execute (start/stop, publish) and cleanup tasks
// to make the runner stateless
InstanceInfo InstanceInfo
GatewayHost string
RoutingKey string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/check.go | types/check.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/json"
"github.com/harness/gitness/types/enum"
)
type Check struct {
ID int64 `json:"id"`
CreatedBy int64 `json:"-"` // clients will use "reported_by"
Created int64 `json:"created,omitempty"`
Updated int64 `json:"updated,omitempty"`
RepoID int64 `json:"-"` // status checks are always returned for a commit in a repository
CommitSHA string `json:"-"` // status checks are always returned for a commit in a repository
Identifier string `json:"identifier"`
Status enum.CheckStatus `json:"status"`
Summary string `json:"summary,omitempty"`
Link string `json:"link,omitempty"`
Metadata json.RawMessage `json:"metadata"`
Started int64 `json:"started,omitempty"`
Ended int64 `json:"ended,omitempty"`
Payload CheckPayload `json:"payload"`
ReportedBy *PrincipalInfo `json:"reported_by,omitempty"`
}
// TODO [CODE-1363]: remove after identifier migration.
func (c Check) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias Check
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(c),
UID: c.Identifier,
})
}
type CheckResult struct {
Identifier string `json:"identifier" db:"check_uid"`
Status enum.CheckStatus `json:"status" db:"check_status"`
}
// TODO [CODE-1363]: remove after identifier migration.
func (s CheckResult) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias CheckResult
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(s),
UID: s.Identifier,
})
}
type CheckPayload struct {
Version string `json:"version"`
Kind enum.CheckPayloadKind `json:"kind"`
Data json.RawMessage `json:"data"`
}
// CheckListOptions holds list status checks query parameters.
type CheckListOptions struct {
ListQueryFilter
}
// CheckRecentOptions holds list recent status check query parameters.
type CheckRecentOptions struct {
Query string
Since int64
}
type CheckPayloadText struct {
Details string `json:"details"`
}
// CheckPayloadInternal is for internal use for more seamless integration for
// Harness CI status checks.
type CheckPayloadInternal struct {
Number int64 `json:"execution_number"`
RepoID int64 `json:"repo_id"`
PipelineID int64 `json:"pipeline_id"`
}
type PullReqChecks struct {
CommitSHA string `json:"commit_sha"`
Checks []PullReqCheck `json:"checks"`
}
type PullReqCheck struct {
Required bool `json:"required"`
Bypassable bool `json:"bypassable"`
Check Check `json:"check"`
}
type CheckCountSummary struct {
Pending int `json:"pending"`
Running int `json:"running"`
Success int `json:"success"`
Failure int `json:"failure"`
Error int `json:"error"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/list_filters.go | types/list_filters.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 types
// ListQueryFilter has pagination related info and a query param.
type ListQueryFilter struct {
Pagination
Query string `json:"query"`
}
type CreatedFilter struct {
CreatedGt int64 `json:"created_gt"`
CreatedLt int64 `json:"created_lt"`
}
type UpdatedFilter struct {
UpdatedGt int64 `json:"updated_gt"`
UpdatedLt int64 `json:"updated_lt"`
}
type EditedFilter struct {
EditedGt int64 `json:"edited_gt"`
EditedLt int64 `json:"edited_lt"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/path_test.go | types/path_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 types
import (
"encoding/json"
"testing"
)
func TestSpacePathSegment_MarshalJSON(t *testing.T) {
t.Run("marshal with all fields", func(t *testing.T) {
segment := SpacePathSegment{
ID: 123,
Identifier: "test-identifier",
IsPrimary: true,
SpaceID: 456,
ParentID: 789,
CreatedBy: 111,
Created: 1234567890,
Updated: 1234567900,
}
data, err := json.Marshal(segment)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var result map[string]any
if err := json.Unmarshal(data, &result); err != nil {
t.Fatalf("failed to unmarshal result: %v", err)
}
// Check that uid field is present and matches identifier
uid, ok := result["uid"].(string)
if !ok {
t.Error("uid field not found or not a string")
}
if uid != "test-identifier" {
t.Errorf("expected uid to be 'test-identifier', got %s", uid)
}
// Check that identifier field is also present
identifier, ok := result["identifier"].(string)
if !ok {
t.Error("identifier field not found or not a string")
}
if identifier != "test-identifier" {
t.Errorf("expected identifier to be 'test-identifier', got %s", identifier)
}
// Check other fields
if isPrimary, ok := result["is_primary"].(bool); !ok || !isPrimary {
t.Errorf("expected is_primary to be true, got %v", result["is_primary"])
}
if spaceID, ok := result["space_id"].(float64); !ok || int64(spaceID) != 456 {
t.Errorf("expected space_id to be 456, got %v", result["space_id"])
}
})
t.Run("marshal with empty identifier", func(t *testing.T) {
segment := SpacePathSegment{
ID: 1,
Identifier: "",
IsPrimary: false,
SpaceID: 2,
}
data, err := json.Marshal(segment)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var result map[string]any
if err := json.Unmarshal(data, &result); err != nil {
t.Fatalf("failed to unmarshal result: %v", err)
}
// Check that uid field is present and empty
uid, ok := result["uid"].(string)
if !ok {
t.Error("uid field not found or not a string")
}
if uid != "" {
t.Errorf("expected uid to be empty, got %s", uid)
}
})
t.Run("marshal zero values", func(t *testing.T) {
segment := SpacePathSegment{}
data, err := json.Marshal(segment)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var result map[string]any
if err := json.Unmarshal(data, &result); err != nil {
t.Fatalf("failed to unmarshal result: %v", err)
}
// Check that uid field is present and empty
uid, ok := result["uid"].(string)
if !ok {
t.Error("uid field not found or not a string")
}
if uid != "" {
t.Errorf("expected uid to be empty, got %s", uid)
}
// Check that identifier field is also present and empty
identifier, ok := result["identifier"].(string)
if !ok {
t.Error("identifier field not found or not a string")
}
if identifier != "" {
t.Errorf("expected identifier to be empty, got %s", identifier)
}
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/connector_auth.go | types/connector_auth.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"fmt"
"github.com/harness/gitness/types/enum"
)
// ConnectorAuth represents the authentication configuration for a connector.
type ConnectorAuth struct {
AuthType enum.ConnectorAuthType `json:"type"`
Basic *BasicAuthCreds `json:"basic,omitempty"`
Bearer *BearerTokenCreds `json:"bearer,omitempty"`
}
// BasicAuthCreds represents credentials for basic authentication.
type BasicAuthCreds struct {
Username string `json:"username"`
Password SecretRef `json:"password"`
}
type BearerTokenCreds struct {
Token SecretRef `json:"token"`
}
func (c *ConnectorAuth) Validate() error {
switch c.AuthType {
case enum.ConnectorAuthTypeBasic:
if c.Basic == nil {
return fmt.Errorf("basic auth credentials are required")
}
if c.Basic.Username == "" || c.Basic.Password.Identifier == "" {
return fmt.Errorf("basic auth credentials are required")
}
case enum.ConnectorAuthTypeBearer:
if c.Bearer == nil {
return fmt.Errorf("bearer token credentials are required")
}
if c.Bearer.Token.Identifier == "" {
return fmt.Errorf("bearer token is required")
}
default:
return fmt.Errorf("unsupported auth type: %s", c.AuthType)
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/gitspace_settings.go | types/gitspace_settings.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/json"
"fmt"
"reflect"
"slices"
"sort"
"strings"
"github.com/harness/gitness/types/enum"
)
type GitspaceSettingsFilter struct {
ListQueryFilter
}
type CriteriaKey string
type SettingsData struct {
Data map[string]any `json:"data,omitempty"` // generic, user-defined
Criteria GitspaceSettingsCriteria `json:"criteria,omitempty"` // criteria for the settings
}
type GitspaceSettings struct {
ID int64 `json:"-"`
Settings SettingsData `json:"settings"`
SettingsType enum.GitspaceSettingsType `json:"settings_type,omitempty"`
CriteriaKey CriteriaKey `json:"criteria_key,omitempty"`
SpaceID int64 `json:"-"`
Created int64 `json:"created,omitempty"`
Updated int64 `json:"updated,omitempty"`
}
type GitspaceSettingsCriteria map[string]any
var ApplyAlwaysToSpaceCriteria = GitspaceSettingsCriteria{}
func flattenCriteria(prefix string, input map[string]any, out map[string]string) {
const maxDepth = 10 // Add depth protection
flattenCriteriaWithDepth(prefix, input, out, 0, maxDepth)
}
func flattenCriteriaWithDepth(prefix string, input map[string]any, out map[string]string, depth, maxDepth int) {
if depth > maxDepth {
return
}
for k, v := range input {
key := k
if prefix != "" {
key = prefix + "." + k
}
switch child := v.(type) {
case map[string]any:
flattenCriteriaWithDepth(key, child, out, depth+1, maxDepth)
default:
out[key] = fmt.Sprintf("%v", v)
}
}
}
func (c GitspaceSettingsCriteria) ToKey() (CriteriaKey, error) {
if len(c) == 0 {
return "", nil
}
flat := make(map[string]string)
flattenCriteria("", c, flat)
keys := make([]string, 0, len(flat))
for k := range flat {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys)*2)
for _, k := range keys {
parts = append(parts, k, flat[k])
}
return CriteriaKey(strings.Join(parts, "/")), nil
}
type IDESettings struct {
AccessList *AccessList[enum.IDEType] `json:"access_list,omitempty"` // Access control for IDEs
DisableSSH bool `json:"disable_ssh"`
}
type AccessList[T comparable] struct {
Mode ListMode `json:"mode"`
List []T `json:"list"`
}
func (a *AccessList[T]) IsAllowed(item T) bool {
if a == nil || len(a.List) == 0 {
return true // If no list, assume unrestricted
}
found := slices.Contains(a.List, item)
if a.Mode == ListModeAllow {
return found
}
// ListModeDeny
return !found
}
func (a *AccessList[T]) Remove(item T) bool {
if a == nil || len(a.List) == 0 {
return false
}
for i, entry := range a.List {
if entry == item {
a.List = append(a.List[:i], a.List[i+1:]...)
return true
}
}
return false
}
type ListMode string
const (
ListModeAllow ListMode = "allow"
ListModeDeny ListMode = "deny"
)
type SCMProviderSettings struct {
AccessList *AccessList[enum.GitspaceCodeRepoType] `json:"access_list,omitempty"` // Allow/Deny list for SCM providers
}
type DevcontainerSettings struct {
DevcontainerImage DevcontainerImage `json:"devcontainer_image"` // Devcontainer image settings
}
type DevcontainerImage struct {
AccessList *AccessList[string] `json:"access_list,omitempty"` // Allow/Deny list for container images
ImageConnectorRef string `json:"image_connector_ref,omitempty"` // Connector reference for the image
ImageName string `json:"image_name,omitempty"` // Name of the container image
}
type GitspaceConfigSettings struct {
IDEs IDESettings `json:"ide"` // allow list of IDEs
SCMProviders SCMProviderSettings `json:"scm"` // allow list of SCMs
Devcontainer DevcontainerSettings `json:"devcontainer"` // allow list of devcontainer images
}
type InfraProviderSettings struct {
AccessList *AccessList[string] `json:"access_list,omitempty"`
AutoStoppingTimeInMins *int `json:"auto_stopping_time_in_mins,omitempty"`
InfraProviderType enum.InfraProviderType `json:"infra_provider_type,omitempty"`
}
var settingsTypeRegistry = map[enum.GitspaceSettingsType]reflect.Type{
enum.SettingsTypeInfraProvider: reflect.TypeOf(InfraProviderSettings{}),
enum.SettingsTypeGitspaceConfig: reflect.TypeOf(GitspaceConfigSettings{}),
}
func DecodeSettings[T any](data map[string]any) (*T, error) {
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
var out T
if err := json.Unmarshal(jsonData, &out); err != nil {
return nil, err
}
return &out, nil
}
func ValidateAndDecodeSettings(settingsType enum.GitspaceSettingsType, data map[string]any) (any, error) {
typ, ok := settingsTypeRegistry[settingsType]
if !ok {
return nil, fmt.Errorf("no schema registered for settings type: %s", settingsType)
}
// Allocate a new struct
ptr := reflect.New(typ).Interface()
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
if err := json.Unmarshal(jsonData, ptr); err != nil {
return nil, fmt.Errorf("schema mismatch: %w", err)
}
return ptr, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/pullreq_activity_metadata.go | types/pullreq_activity_metadata.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 types
// PullReqActivityMetadata contains metadata related to pull request activity.
type PullReqActivityMetadata struct {
Suggestions *PullReqActivitySuggestionsMetadata `json:"suggestions,omitempty"`
Mentions *PullReqActivityMentionsMetadata `json:"mentions,omitempty"`
}
func (m *PullReqActivityMetadata) IsEmpty() bool {
// WARNING: This only works as long as there's no non-comparable fields in the struct.
return m == nil || *m == PullReqActivityMetadata{}
}
type PullReqActivityMetadataUpdate interface {
apply(m *PullReqActivityMetadata)
}
type pullReqActivityMetadataUpdateFunc func(m *PullReqActivityMetadata)
func (f pullReqActivityMetadataUpdateFunc) apply(m *PullReqActivityMetadata) {
f(m)
}
func WithPullReqActivityMetadataUpdate(f func(m *PullReqActivityMetadata)) PullReqActivityMetadataUpdate {
return pullReqActivityMetadataUpdateFunc(f)
}
// PullReqActivitySuggestionsMetadata contains metadata for code comment suggestions.
type PullReqActivitySuggestionsMetadata struct {
CheckSums []string `json:"check_sums,omitempty"`
AppliedCheckSum string `json:"applied_check_sum,omitempty"`
AppliedCommitSHA string `json:"applied_commit_sha,omitempty"`
}
func (m *PullReqActivitySuggestionsMetadata) IsEmpty() bool {
return len(m.CheckSums) == 0 && m.AppliedCheckSum == "" && m.AppliedCommitSHA == ""
}
func WithPullReqActivitySuggestionsMetadataUpdate(
f func(m *PullReqActivitySuggestionsMetadata),
) PullReqActivityMetadataUpdate {
return pullReqActivityMetadataUpdateFunc(func(m *PullReqActivityMetadata) {
if m.Suggestions == nil {
m.Suggestions = &PullReqActivitySuggestionsMetadata{}
}
f(m.Suggestions)
if m.Suggestions.IsEmpty() {
m.Suggestions = nil
}
})
}
// PullReqActivityMentionsMetadata contains metadata for code comment mentions.
type PullReqActivityMentionsMetadata struct {
IDs []int64 `json:"ids,omitempty"`
UserGroupIDs []int64 `json:"user_group_ids,omitempty"`
}
func (m *PullReqActivityMentionsMetadata) IsEmpty() bool {
return len(m.IDs) == 0 && len(m.UserGroupIDs) == 0
}
func WithPullReqActivityMentionsMetadataUpdate(
f func(m *PullReqActivityMentionsMetadata),
) PullReqActivityMetadataUpdate {
return pullReqActivityMetadataUpdateFunc(func(m *PullReqActivityMetadata) {
if m.Mentions == nil {
m.Mentions = &PullReqActivityMentionsMetadata{}
}
f(m.Mentions)
if m.Mentions.IsEmpty() {
m.Mentions = nil
}
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/code_comment.go | types/code_comment.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 types
type CodeComment struct {
ID int64 `db:"pullreq_activity_id"`
Version int64 `db:"pullreq_activity_version"`
Updated int64 `db:"pullreq_activity_updated"`
CodeCommentFields
}
type CodeCommentFields struct {
Outdated bool `db:"pullreq_activity_outdated" json:"outdated"`
MergeBaseSHA string `db:"pullreq_activity_code_comment_merge_base_sha" json:"merge_base_sha"`
SourceSHA string `db:"pullreq_activity_code_comment_source_sha" json:"source_sha"`
Path string `db:"pullreq_activity_code_comment_path" json:"path"`
LineNew int `db:"pullreq_activity_code_comment_line_new" json:"line_new"`
SpanNew int `db:"pullreq_activity_code_comment_span_new" json:"span_new"`
LineOld int `db:"pullreq_activity_code_comment_line_old" json:"line_old"`
SpanOld int `db:"pullreq_activity_code_comment_span_old" json:"span_old"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/pullreq.go | types/pullreq.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"github.com/harness/gitness/types/enum"
"github.com/gotidy/ptr"
)
// PullReq represents a pull request.
type PullReq struct {
ID int64 `json:"-"` // not returned, it's an internal field
Version int64 `json:"-"` // not returned, it's an internal field
Number int64 `json:"number"`
CreatedBy int64 `json:"-"` // not returned, because the author info is in the Author field
Created int64 `json:"created"`
Updated int64 `json:"updated"`
Edited int64 `json:"edited"` // TODO: Remove. Field Edited is equal to Updated
Closed *int64 `json:"closed,omitempty"`
State enum.PullReqState `json:"state"`
IsDraft bool `json:"is_draft"`
CommentCount int `json:"-"` // returned as "conversations" in the Stats
UnresolvedCount int `json:"-"` // returned as "unresolved_count" in the Stats
Title string `json:"title"`
Description string `json:"description"`
SourceRepoID *int64 `json:"source_repo_id"`
SourceBranch string `json:"source_branch"`
SourceSHA string `json:"source_sha"`
TargetRepoID int64 `json:"target_repo_id"`
TargetBranch string `json:"target_branch"`
ActivitySeq int64 `json:"-"` // not returned, because it's a server's internal field
MergedBy *int64 `json:"-"` // not returned, because the merger info is in the Merger field
Merged *int64 `json:"merged"`
MergeMethod *enum.MergeMethod `json:"merge_method"`
MergeViolationsBypassed *bool `json:"merge_violations_bypassed"`
MergeTargetSHA *string `json:"merge_target_sha"`
MergeBaseSHA string `json:"merge_base_sha"`
MergeSHA *string `json:"-"` // TODO: either remove or ensure it's being set (merge dry-run)
MergeCheckStatus enum.MergeCheckStatus `json:"merge_check_status"`
MergeConflicts []string `json:"merge_conflicts,omitempty"`
RebaseCheckStatus enum.MergeCheckStatus `json:"rebase_check_status"`
RebaseConflicts []string `json:"rebase_conflicts,omitempty"`
Author PrincipalInfo `json:"author"`
Merger *PrincipalInfo `json:"merger"`
Stats PullReqStats `json:"stats"`
Labels []*LabelPullReqAssignmentInfo `json:"labels,omitempty"`
CheckSummary *CheckCountSummary `json:"check_summary,omitempty"`
Rules []RuleInfo `json:"rules,omitempty"`
SourceRepo *RepositoryCore `json:"source_repo,omitempty"`
}
func (pr *PullReq) UpdateMergeOutcome(method enum.MergeMethod, conflictFiles []string) {
switch method {
case enum.MergeMethodMerge, enum.MergeMethodSquash:
if len(conflictFiles) > 0 {
pr.MergeCheckStatus = enum.MergeCheckStatusConflict
pr.MergeConflicts = conflictFiles
} else {
pr.MergeCheckStatus = enum.MergeCheckStatusMergeable
pr.MergeConflicts = nil
}
case enum.MergeMethodRebase:
if len(conflictFiles) > 0 {
pr.RebaseCheckStatus = enum.MergeCheckStatusConflict
pr.RebaseConflicts = conflictFiles
} else {
pr.RebaseCheckStatus = enum.MergeCheckStatusMergeable
pr.RebaseConflicts = nil
}
case enum.MergeMethodFastForward:
// fast-forward merge can't have conflicts
}
}
func (pr *PullReq) MarkAsMergeUnchecked() {
pr.MergeCheckStatus = enum.MergeCheckStatusUnchecked
pr.MergeConflicts = nil
pr.RebaseCheckStatus = enum.MergeCheckStatusUnchecked
pr.RebaseConflicts = nil
}
func (pr *PullReq) MarkAsMergeable() {
pr.MergeCheckStatus = enum.MergeCheckStatusMergeable
pr.MergeConflicts = nil
}
func (pr *PullReq) MarkAsRebaseable() {
pr.RebaseCheckStatus = enum.MergeCheckStatusMergeable
pr.RebaseConflicts = nil
}
func (pr *PullReq) MarkAsMerged() {
pr.MergeCheckStatus = enum.MergeCheckStatusMergeable
pr.MergeConflicts = nil
pr.RebaseCheckStatus = enum.MergeCheckStatusMergeable
pr.RebaseConflicts = nil
}
// DiffStats holds summary of changes in git:
// total number of commits, number modified files and number of line changes.
type DiffStats struct {
Commits *int64 `json:"commits,omitempty"`
FilesChanged *int64 `json:"files_changed,omitempty"`
Additions *int64 `json:"additions,omitempty"`
Deletions *int64 `json:"deletions,omitempty"`
}
func NewDiffStats(commitCount, fileCount, additions, deletions int) DiffStats {
return DiffStats{
Commits: ptr.Int64(int64(commitCount)),
FilesChanged: ptr.Int64(int64(fileCount)),
Additions: ptr.Int64(int64(additions)),
Deletions: ptr.Int64(int64(deletions)),
}
}
// PullReqStats shows Diff statistics and number of conversations.
type PullReqStats struct {
DiffStats
Conversations int `json:"conversations,omitempty"`
UnresolvedCount int `json:"unresolved_count,omitempty"`
}
// PullReqFilter stores pull request query parameters.
type PullReqFilter struct {
Page int `json:"page"`
Size int `json:"size"`
Query string `json:"query"`
CreatedBy []int64 `json:"created_by"`
SourceRepoID int64 `json:"-"` // caller should use source_repo_ref
SourceRepoRef string `json:"source_repo_ref"`
SourceBranch string `json:"source_branch"`
TargetRepoID int64 `json:"-"`
TargetBranch string `json:"target_branch"`
States []enum.PullReqState `json:"state"`
Sort enum.PullReqSort `json:"sort"`
Order enum.Order `json:"order"`
LabelID []int64 `json:"label_id"`
ValueID []int64 `json:"value_id"`
CommenterID int64 `json:"commenter_id"`
ReviewerID int64 `json:"reviewer_id"`
ReviewDecisions []enum.PullReqReviewDecision `json:"review_decisions"`
MentionedID int64 `json:"mentioned_id"`
ExcludeDescription bool `json:"exclude_description"`
CreatedFilter
UpdatedFilter
EditedFilter
PullReqMetadataOptions
// internal use only
SpaceIDs []int64
RepoIDBlacklist []int64
}
type PullReqMetadataOptions struct {
IncludeGitStats bool `json:"include_git_stats"`
IncludeChecks bool `json:"include_checks"`
IncludeRules bool `json:"include_rules"`
}
// PullReqReview holds pull request review.
type PullReqReview struct {
ID int64 `json:"id"`
CreatedBy int64 `json:"created_by"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
PullReqID int64 `json:"pullreq_id"`
Decision enum.PullReqReviewDecision `json:"decision"`
SHA string `json:"sha"`
}
// PullReqReviewer holds pull request reviewer.
type PullReqReviewer struct {
PullReqID int64 `json:"-"`
PrincipalID int64 `json:"-"`
CreatedBy int64 `json:"-"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
RepoID int64 `json:"-"`
Type enum.PullReqReviewerType `json:"type"`
LatestReviewID *int64 `json:"latest_review_id"`
ReviewDecision enum.PullReqReviewDecision `json:"review_decision"`
SHA string `json:"sha"`
Reviewer PrincipalInfo `json:"reviewer"`
AddedBy PrincipalInfo `json:"added_by"`
}
type UserGroupReviewer struct {
PullReqID int64 `json:"-"`
UserGroupID int64 `json:"-"`
CreatedBy int64 `json:"-"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
RepoID int64 `json:"-"`
UserGroup UserGroupInfo `json:"user_group"`
AddedBy PrincipalInfo `json:"added_by"`
// invdividual decisions by group users
UserDecisions []ReviewerEvaluation `json:"user_decisions,omitempty"`
// derived user group decision: change_req > approved > reviewed > pending
Decision enum.PullReqReviewDecision `json:"decision,omitempty"`
SHA string `json:"sha,omitempty"`
}
type ReviewerEvaluation struct {
Decision enum.PullReqReviewDecision `json:"decision"`
SHA string `json:"sha,omitempty"`
Reviewer PrincipalInfo `json:"reviewer"`
Updated int64 `json:"updated"`
}
// PullReqFileView represents a file reviewed entry for a given pr and principal.
// NOTE: keep api lightweight and don't return unnecessary extra data.
type PullReqFileView struct {
PullReqID int64 `json:"-"`
PrincipalID int64 `json:"-"`
Path string `json:"path"`
SHA string `json:"sha"`
Obsolete bool `json:"obsolete"`
Created int64 `json:"-"`
Updated int64 `json:"-"`
}
type DefaultReviewerApprovalsResponse struct {
MinimumRequiredCount int `json:"minimum_required_count"`
MinimumRequiredCountLatest int `json:"minimum_required_count_latest"`
CurrentCount int `json:"current_count"`
PrincipalIDs []int64 `json:"-"`
PrincipalInfos []*PrincipalInfo `json:"principals"`
UserGroupIDs []int64 `json:"-"`
UserGroupInfos []*UserGroupInfo `json:"user_groups"`
Evaluations []*ReviewerEvaluation `json:"evaluations"`
}
type MergeResponse struct {
SHA string `json:"sha,omitempty"`
BranchDeleted bool `json:"branch_deleted,omitempty"`
RuleViolations []RuleViolations `json:"rule_violations,omitempty"`
// values only returned on dryrun
DryRunRules bool `json:"dry_run_rules,omitempty"`
DryRun bool `json:"dry_run,omitempty"`
Mergeable bool `json:"mergeable,omitempty"`
ConflictFiles []string `json:"conflict_files,omitempty"`
AllowedMethods []enum.MergeMethod `json:"allowed_methods,omitempty"`
MinimumRequiredApprovalsCount int `json:"minimum_required_approvals_count,omitempty"`
MinimumRequiredApprovalsCountLatest int `json:"minimum_required_approvals_count_latest,omitempty"`
DefaultReviewerApprovals []*DefaultReviewerApprovalsResponse `json:"default_reviewer_aprovals,omitempty"`
RequiresCodeOwnersApproval bool `json:"requires_code_owners_approval,omitempty"`
RequiresCodeOwnersApprovalLatest bool `json:"requires_code_owners_approval_latest,omitempty"`
RequiresCommentResolution bool `json:"requires_comment_resolution,omitempty"`
RequiresNoChangeRequests bool `json:"requires_no_change_requests,omitempty"`
}
type MergeViolations struct {
Message string `json:"message,omitempty"`
ConflictFiles []string `json:"conflict_files,omitempty"`
RuleViolations []RuleViolations `json:"rule_violations,omitempty"`
}
type PullReqRepo struct {
PullRequest *PullReq `json:"pull_request"`
Repository *RepositoryCore `json:"repository"`
}
type RevertResponse struct {
Branch string `json:"branch"`
Commit Commit `json:"commit"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/space.go | types/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 types
import (
"github.com/harness/gitness/types/enum"
)
type SpaceCore struct {
ID int64 `json:"id"`
ParentID int64 `json:"parent_id"`
Path string `json:"path"`
Identifier string `json:"identifier"`
}
/*
Space represents a space.
There isn't a one-solves-all hierarchical data structure for DBs,
so for now we are using a mix of materialized paths and adjacency list.
Every space stores its parent, and a space's path (and aliases) is stored in a separate table.
PRO: Quick lookup of childs, quick lookup based on fqdn (apis).
CON: we require a separate table.
Interesting reads:
https://stackoverflow.com/questions/4048151/what-are-the-options-for-storing-hierarchical-data-in-a-relational-database
https://www.slideshare.net/billkarwin/models-for-hierarchical-data
*/
type Space struct {
ID int64 `json:"id"`
Version int64 `json:"-"`
ParentID int64 `json:"parent_id"`
Path string `json:"path"`
Identifier string `json:"identifier"`
Description string `json:"description"`
CreatedBy int64 `json:"created_by"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
Deleted *int64 `json:"deleted,omitempty"`
}
func (s *Space) Core() *SpaceCore {
return &SpaceCore{
ID: s.ID,
ParentID: s.ParentID,
Path: s.Path,
Identifier: s.Identifier,
}
}
type SpaceParentData struct {
ID int64 `json:"id"`
Identifier string `json:"identifier"`
ParentID int64 `json:"parent_id"`
}
// SpaceFilter stores spaces query parameters.
type SpaceFilter struct {
Page int `json:"page"`
Size int `json:"size"`
Query string `json:"query"`
Sort enum.SpaceAttr `json:"sort"`
Order enum.Order `json:"order"`
DeletedAt *int64 `json:"deleted_at,omitempty"`
DeletedBeforeOrAt *int64 `json:"deleted_before_or_at,omitempty"`
Recursive bool `json:"recursive"`
}
type SpaceStorage struct {
ID int64 `json:"id"`
Identifier string `json:"identifier"`
Size int64 `json:"size"`
LFSSize int64 `json:"lfs_size"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/search.go | types/search.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 types
type (
SearchInput struct {
Query string `json:"query"`
// RepoPaths contains the paths of repositories to search in
RepoPaths []string `json:"repo_paths"`
// SpacePaths contains the paths of spaces to search in
SpacePaths []string `json:"space_paths"`
// MaxResultCount is the maximum number of results to return
MaxResultCount int `json:"max_result_count"`
// EnableRegex enables regex search on the query
EnableRegex bool `json:"enable_regex"`
// Search all the repos in a space and its subspaces recursively.
// Valid only when spacePaths is set.
Recursive bool `json:"recursive"`
}
SearchResult struct {
FileMatches []FileMatch `json:"file_matches"`
Stats SearchStats `json:"stats"`
}
SearchStats struct {
TotalFiles int `json:"total_files"`
TotalMatches int `json:"total_matches"`
}
FileMatch struct {
FileName string `json:"file_name"`
RepoID int64 `json:"-"`
RepoPath string `json:"repo_path"`
RepoBranch string `json:"repo_branch"`
Language string `json:"language"`
Matches []Match `json:"matches"`
}
// Match holds the per line data.
Match struct {
// LineNum is the line number of the match
LineNum int `json:"line_num"`
// Fragments holds the matched fragments within the line
Fragments []Fragment `json:"fragments"`
// Before holds the content from the line immediately preceding the line where the match was found
Before string `json:"before"`
// After holds the content from the line immediately following the line where the match was found
After string `json:"after"`
}
// Fragment holds data of a single contiguous match within a line.
Fragment struct {
Pre string `json:"pre"` // the string before the match within the line
Match string `json:"match"` // the matched string
Post string `json:"post"` // the string after the match within the line
}
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/connector_config.go | types/connector_config.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 types
import (
"fmt"
"github.com/harness/gitness/types/enum"
)
// ConnectorConfig is a list of all the connector and their associated config.
type ConnectorConfig struct {
Github *GithubConnectorData `json:"github,omitempty"`
}
func (c ConnectorConfig) Validate(typ enum.ConnectorType) error {
switch typ {
case enum.ConnectorTypeGithub:
if c.Github != nil {
return c.Github.Validate()
}
return fmt.Errorf("github connector config is required")
default:
return fmt.Errorf("connector type %s is not supported", typ)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/favorite.go | types/favorite.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 types
import "github.com/harness/gitness/types/enum"
type FavoriteResource struct {
ID int64 `json:"resource_id"`
Type enum.ResourceType `json:"resource_type"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/config_test.go | types/config_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 types
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/rebase.go | types/rebase.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 types
import "github.com/harness/gitness/git/sha"
type RebaseResponse struct {
AlreadyAncestor bool `json:"already_ancestor,omitempty"`
NewHeadBranchSHA sha.SHA `json:"new_head_branch_sha"`
RuleViolations []RuleViolations `json:"rule_violations,omitempty"`
DryRunRules bool `json:"dry_run_rules,omitempty"`
DryRun bool `json:"dry_run,omitempty"`
ConflictFiles []string `json:"conflict_files,omitempty"`
}
type SquashResponse struct {
NewHeadBranchSHA sha.SHA `json:"new_head_branch_sha"`
RuleViolations []RuleViolations `json:"rule_violations,omitempty"`
DryRunRules bool `json:"dry_run_rules,omitempty"`
DryRun bool `json:"dry_run,omitempty"`
ConflictFiles []string `json:"conflict_files,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/public_key.go | types/public_key.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/json"
"github.com/harness/gitness/types/enum"
)
type PublicKey struct {
// ID of the key. Frontend doesn't need it.
ID int64 `json:"-"`
// PrincipalID who owns the key.
// Not returned in API response because the API always returns keys for the same user.
PrincipalID int64 `json:"-"`
Created int64 `json:"created"`
// Verified holds the timestamp when the key was successfully used to access the system.
Verified *int64 `json:"verified"`
Identifier string `json:"identifier"`
// Usage holds the allowed usage for the key - authorization or signature verification.
Usage enum.PublicKeyUsage `json:"usage"`
// Fingerprint is a short hash sum of the key. Useful for quick key comparison.
// The value is indexed in the database.
Fingerprint string `json:"fingerprint"`
// Content holds the original uploaded public key data.
Content string `json:"-"`
Comment string `json:"comment"`
// Type of the key - the algorithm used to generate the key.
Type string `json:"type"`
// Scheme indicates if it's SSH or PGP key.
Scheme enum.PublicKeyScheme `json:"scheme"`
// ValidFrom and ValidTo are validity period for the key.
// If they have valid values, the key should NOT be used outside the period.
ValidFrom *int64 `json:"valid_from"`
ValidTo *int64 `json:"valid_to"`
// RevocationReason is the reason why the key has been revoked.
// If a key has a RevocationReason it should also have ValidTo timestamp set.
RevocationReason *enum.RevocationReason `json:"revocation_reason"`
// Metadata holds additional key metadata info for the UI (for PGP keys).
Metadata json.RawMessage `json:"metadata"`
}
type PublicKeyFilter struct {
ListQueryFilter
Sort enum.PublicKeySort
Order enum.Order
Usages []enum.PublicKeyUsage
Schemes []enum.PublicKeyScheme
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/platform_connector.go | types/platform_connector.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 types
const (
ecrRegistryUserName = "AWS"
UnknownPlatformConnectorType PlatformConnectorType = "Unknown"
ArtifactoryPlatformConnectorType PlatformConnectorType = "Artifactory"
DockerRegistryPlatformConnectorType PlatformConnectorType = "DockerRegistry"
AWSPlatformConnectorType PlatformConnectorType = "Aws"
UnknownPlatformConnectorAuthType PlatformConnectorAuthType = "unknown"
UserNamePasswordPlatformConnectorAuthType PlatformConnectorAuthType = "UsernamePassword"
AnonymousPlatformConnectorAuthType PlatformConnectorAuthType = "Anonymous"
UnknownAWSCredentialsType AwsCredentialsType = "unknown"
ManualConfigAWSCredentialsType AwsCredentialsType = "ManualConfig"
)
var (
platformConnectorTypeMapping = map[string]PlatformConnectorType{
ArtifactoryPlatformConnectorType.String(): ArtifactoryPlatformConnectorType,
DockerRegistryPlatformConnectorType.String(): DockerRegistryPlatformConnectorType,
AWSPlatformConnectorType.String(): AWSPlatformConnectorType,
}
platformConnectorAuthTypeMapping = map[string]PlatformConnectorAuthType{
UserNamePasswordPlatformConnectorAuthType.String(): UserNamePasswordPlatformConnectorAuthType,
AnonymousPlatformConnectorAuthType.String(): AnonymousPlatformConnectorAuthType,
}
awsCredentialsTypeMapping = map[string]AwsCredentialsType{
ManualConfigAWSCredentialsType.String(): ManualConfigAWSCredentialsType,
}
)
type PlatformConnectorType string
func (t PlatformConnectorType) String() string { return string(t) }
func ToPlatformConnectorType(s string) PlatformConnectorType {
if val, ok := platformConnectorTypeMapping[s]; ok {
return val
}
return UnknownPlatformConnectorType
}
type PlatformConnectorAuthType string
func (t PlatformConnectorAuthType) String() string { return string(t) }
func ToPlatformConnectorAuthType(s string) PlatformConnectorAuthType {
if val, ok := platformConnectorAuthTypeMapping[s]; ok {
return val
}
return UnknownPlatformConnectorAuthType
}
type AwsCredentialsType string
func (t AwsCredentialsType) String() string { return string(t) }
func ToAwsCredentialsType(s string) AwsCredentialsType {
if val, ok := awsCredentialsTypeMapping[s]; ok {
return val
}
return UnknownAWSCredentialsType
}
type PlatformConnector struct {
ID string
Name string
ConnectorSpec PlatformConnectorSpec
}
type PlatformConnectorSpec struct {
Type PlatformConnectorType
// ArtifactoryURL is for ArtifactoryPlatformConnectorType
ArtifactoryURL string
// DockerRegistryURL is for DockerRegistryPlatformConnectorType
DockerRegistryURL string
// AwsECRRegistryURL is for AWSPlatformConnectorType
AwsECRRegistryURL string
// AwsCredentials is for AWSPlatformConnectorType
AwsCredentials AwsCredentials
// AuthSpec is for ArtifactoryPlatformConnectorType and DockerRegistryPlatformConnectorType
AuthSpec PlatformConnectorAuthSpec
EnabledProxy bool
}
type AwsCredentials struct {
Type AwsCredentialsType
Region string
AccessToken MaskSecret
AccessKey MaskSecret
AccessKeyRef string
SecretKeyRef string
SecretKey MaskSecret
SessionTokenRef string
SessionToken MaskSecret
}
// PlatformConnectorAuthSpec provide auth details.
// PlatformConnectorAuthSpec is empty for AnonymousPlatformConnectorAuthType.
type PlatformConnectorAuthSpec struct {
AuthType PlatformConnectorAuthType
// userName can be empty when userName is encrypted.
UserName *MaskSecret
// UserNameRef can be empty when userName is not encrypted
UserNameRef string
Password *MaskSecret
PasswordRef string
}
func (c PlatformConnectorSpec) ExtractRegistryURL() string {
switch c.Type {
case DockerRegistryPlatformConnectorType:
return c.DockerRegistryURL
case ArtifactoryPlatformConnectorType:
return c.ArtifactoryURL
case AWSPlatformConnectorType:
return c.AwsECRRegistryURL
case UnknownPlatformConnectorType:
return ""
default:
return ""
}
}
func (c PlatformConnectorSpec) ExtractRegistryUserName() string {
if (c.Type == DockerRegistryPlatformConnectorType || c.Type == ArtifactoryPlatformConnectorType) &&
c.AuthSpec.AuthType == UserNamePasswordPlatformConnectorAuthType {
return c.AuthSpec.UserName.Value()
} else if c.Type == AWSPlatformConnectorType {
return ecrRegistryUserName
}
return ""
}
func (c PlatformConnectorAuthSpec) ExtractUserNameRef() string {
if c.AuthType == UserNamePasswordPlatformConnectorAuthType {
return c.UserNameRef
}
return ""
}
func (c PlatformConnectorAuthSpec) ExtractPasswordRef() string {
if c.AuthType == UserNamePasswordPlatformConnectorAuthType {
return c.PasswordRef
}
return ""
}
func (c PlatformConnectorSpec) ExtractRegistryAuth() string {
if (c.Type == DockerRegistryPlatformConnectorType || c.Type == ArtifactoryPlatformConnectorType) &&
c.AuthSpec.AuthType == UserNamePasswordPlatformConnectorAuthType &&
c.AuthSpec.Password != nil {
return c.AuthSpec.Password.Value()
} else if c.Type == AWSPlatformConnectorType && c.AwsCredentials.AccessToken.Value() != "" {
return c.AwsCredentials.AccessToken.Value()
}
return ""
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/pagination.go | types/pagination.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 types
// Pagination stores pagination related params.
type Pagination struct {
Page int `json:"page"`
Size int `json:"size"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/repo.go | types/repo.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/json"
"strings"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/types/enum"
)
type RepositoryCore struct {
ID int64 `json:"id" yaml:"id"`
ParentID int64 `json:"parent_id" yaml:"parent_id"`
Identifier string `json:"identifier" yaml:"identifier"`
Path string `json:"path" yaml:"path"`
GitUID string `json:"-" yaml:"-"`
DefaultBranch string `json:"default_branch" yaml:"default_branch"`
ForkID int64 `json:"fork_id" yaml:"fork_id"`
State enum.RepoState `json:"-" yaml:"-"`
Type enum.RepoType `json:"type,omitempty" yaml:"type,omitempty"`
}
func (r *RepositoryCore) GetGitUID() string {
return r.GitUID
}
// Repository represents a code repository.
type Repository struct {
// TODO: int64 ID doesn't match DB
ID int64 `json:"id" yaml:"id"`
Version int64 `json:"-" yaml:"-"`
ParentID int64 `json:"parent_id" yaml:"parent_id"`
Identifier string `json:"identifier" yaml:"identifier"`
Path string `json:"path" yaml:"path"`
Description string `json:"description" yaml:"description"`
CreatedBy int64 `json:"created_by" yaml:"created_by"`
Created int64 `json:"created" yaml:"created"`
Updated int64 `json:"updated" yaml:"updated"`
Deleted *int64 `json:"deleted,omitempty" yaml:"deleted"`
LastGITPush int64 `json:"last_git_push" yaml:"last_git_push"`
// Size of the repository in KiB.
Size int64 `json:"size" yaml:"size" description:"size of the repository in KiB"`
LFSSize int64 `json:"size_lfs" yaml:"lfs_size" description:"size of the repository LFS in KiB"`
// SizeUpdated is the time when the Size was last updated.
SizeUpdated int64 `json:"size_updated" yaml:"size_updated"`
GitUID string `json:"-" yaml:"-"`
DefaultBranch string `json:"default_branch" yaml:"default_branch"`
ForkID int64 `json:"fork_id" yaml:"fork_id"`
PullReqSeq int64 `json:"-" yaml:"-"`
NumForks int `json:"num_forks" yaml:"num_forks"`
NumPulls int `json:"num_pulls" yaml:"num_pulls"`
NumClosedPulls int `json:"num_closed_pulls" yaml:"num_closed_pulls"`
NumOpenPulls int `json:"num_open_pulls" yaml:"num_open_pulls"`
NumMergedPulls int `json:"num_merged_pulls" yaml:"num_merged_pulls"`
State enum.RepoState `json:"state" yaml:"state"`
IsEmpty bool `json:"is_empty,omitempty" yaml:"is_empty"`
// git urls
GitURL string `json:"git_url" yaml:"-"`
GitSSHURL string `json:"git_ssh_url,omitempty" yaml:"-"`
Tags json.RawMessage `json:"tags,omitempty" yaml:"tags"`
Type enum.RepoType `json:"repo_type,omitempty" yaml:"repo_type"`
}
func (r *Repository) Core() *RepositoryCore {
return &RepositoryCore{
ID: r.ID,
ParentID: r.ParentID,
Identifier: r.Identifier,
Path: r.Path,
GitUID: r.GitUID,
ForkID: r.ForkID,
DefaultBranch: r.DefaultBranch,
State: r.State,
Type: r.Type,
}
}
// Clone makes deep copy of repository object.
func (r Repository) Clone() Repository {
var deleted *int64
if r.Deleted != nil {
id := *r.Deleted
deleted = &id
}
r.Deleted = deleted
return r
}
type RepositorySizeInfo struct {
ID int64 `json:"id"`
GitUID string `json:"git_uid"`
// Size of the repository in KiB.
Size int64 `json:"size"`
// LFSSize size of the LFS data in KiB.
LFSSize int64 `json:"lfs_size"`
// SizeUpdated is the time when the Size was last updated.
SizeUpdated int64 `json:"size_updated"`
}
func (r Repository) GetGitUID() string {
return r.GitUID
}
// RepoFilter stores repo query parameters.
type RepoFilter struct {
Page int `json:"page"`
Size int `json:"size"`
Query string `json:"query"`
Sort enum.RepoAttr `json:"sort"`
Order enum.Order `json:"order"`
DeletedAt *int64 `json:"deleted_at,omitempty"`
DeletedBeforeOrAt *int64 `json:"deleted_before_or_at,omitempty"`
// Same tag key can be associated with multiple values
Tags map[string][]string
Recursive bool
OnlyFavoritesFor *int64
Identifiers []string `json:"-"`
}
type RepoCacheKey struct {
SpaceID int64
RepoIdentifier string
}
type RepositoryPullReqSummary struct {
OpenCount int `json:"open_count"`
ClosedCount int `json:"closed_count"`
MergedCount int `json:"merged_count"`
}
type RepositorySummary struct {
DefaultBranchCommitCount int `json:"default_branch_commit_count"`
BranchCount int `json:"branch_count"`
TagCount int `json:"tag_count"`
PullReqSummary RepositoryPullReqSummary `json:"pull_req_summary"`
}
type RepositoryCount struct {
SpaceID int64 `json:"space_id"`
SpaceUID string `json:"space_uid"`
Total int `json:"total"`
}
type RepoTags map[string]string
func (t RepoTags) Sanitize() error {
if len(t) == 0 {
return nil
}
for k, v := range t {
sk, sv := k, v
if err := sanitizeRepoTag(&sk, TagPartTypeKey); err != nil {
return err
}
if err := sanitizeRepoTag(&sv, TagPartTypeValue); err != nil {
return err
}
if sk != k || sv != v {
delete(t, k) // remove old
t[sk] = sv // insert sanitized
}
}
return nil
}
func sanitizeRepoTag(tag *string, typ TagPartType) error {
if tag == nil {
return nil
}
if strings.Contains(*tag, ":") {
return errors.InvalidArgumentf("tag %s cannot contain colon [:]", typ)
}
return SanitizeTag(tag, typ, false)
}
type LinkedRepo struct {
RepoID int64
Version int64
Created int64
Updated int64
LastFullSync int64
ConnectorPath string
ConnectorIdentifier string
ConnectorRepo string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/tag.go | types/tag.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
type CreateCommitTagOutput struct {
CommitTag
DryRunRulesOutput
}
type DeleteCommitTagOutput struct {
DryRunRulesOutput
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/secret.go | types/secret.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 types
import "encoding/json"
type Secret struct {
ID int64 `db:"secret_id" json:"-"`
Description string `db:"secret_description" json:"description"`
SpaceID int64 `db:"secret_space_id" json:"space_id"`
CreatedBy int64 `db:"secret_created_by" json:"created_by"`
Identifier string `db:"secret_uid" json:"identifier"`
Data string `db:"secret_data" json:"-"`
Created int64 `db:"secret_created" json:"created"`
Updated int64 `db:"secret_updated" json:"updated"`
Version int64 `db:"secret_version" json:"-"`
}
// TODO [CODE-1363]: remove after identifier migration.
func (s Secret) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias Secret
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(s),
UID: s.Identifier,
})
}
// Copy makes a copy of the secret without the value.
func (s *Secret) CopyWithoutData() *Secret {
return &Secret{
ID: s.ID,
Description: s.Description,
Identifier: s.Identifier,
SpaceID: s.SpaceID,
Created: s.Created,
Updated: s.Updated,
Version: s.Version,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/multireader_closer.go | types/multireader_closer.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 types
import "io"
type MultiReadCloser struct {
io.Reader
CloseFunc func() error
}
func (m *MultiReadCloser) Close() error {
return m.CloseFunc()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/secret_ref.go | types/secret_ref.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
type SecretRef struct {
Identifier string `json:"identifier"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/multireader_closer_test.go | types/multireader_closer_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 types
import (
"errors"
"io"
"strings"
"testing"
)
func TestMultiReadCloser_Read(t *testing.T) {
content := "test content"
reader := strings.NewReader(content)
closeCalled := false
mrc := &MultiReadCloser{
Reader: reader,
}
// Test reading
buf := make([]byte, len(content))
n, err := mrc.Read(buf)
if err != nil {
t.Fatalf("Read() returned error: %v", err)
}
if n != len(content) {
t.Errorf("Read() returned %d bytes, expected %d", n, len(content))
}
if string(buf) != content {
t.Errorf("Read() returned %q, expected %q", string(buf), content)
}
// Verify close wasn't called yet
if closeCalled {
t.Errorf("CloseFunc was called before Close()")
}
}
func TestMultiReadCloser_Close(t *testing.T) {
reader := strings.NewReader("test")
closeCalled := false
mrc := &MultiReadCloser{
Reader: reader,
CloseFunc: func() error {
closeCalled = true
return nil
},
}
// Test closing
err := mrc.Close()
if err != nil {
t.Fatalf("Close() returned error: %v", err)
}
if !closeCalled {
t.Errorf("CloseFunc was not called")
}
}
func TestMultiReadCloser_CloseError(t *testing.T) {
reader := strings.NewReader("test")
expectedErr := errors.New("close error")
mrc := &MultiReadCloser{
Reader: reader,
CloseFunc: func() error {
return expectedErr
},
}
// Test closing with error
err := mrc.Close()
if !errors.Is(err, expectedErr) {
t.Errorf("Close() returned error %v, expected %v", err, expectedErr)
}
}
func TestMultiReadCloser_ReadAndClose(t *testing.T) {
content := "hello world"
reader := strings.NewReader(content)
closeCalled := false
mrc := &MultiReadCloser{
Reader: reader,
CloseFunc: func() error {
closeCalled = true
return nil
},
}
// Read all content
buf := make([]byte, len(content))
n, err := io.ReadFull(mrc, buf)
if err != nil {
t.Fatalf("ReadFull() returned error: %v", err)
}
if n != len(content) {
t.Errorf("ReadFull() returned %d bytes, expected %d", n, len(content))
}
if string(buf) != content {
t.Errorf("ReadFull() returned %q, expected %q", string(buf), content)
}
// Close
err = mrc.Close()
if err != nil {
t.Fatalf("Close() returned error: %v", err)
}
if !closeCalled {
t.Errorf("CloseFunc was not called")
}
}
func TestMultiReadCloser_MultipleReads(t *testing.T) {
content := "test content for multiple reads"
reader := strings.NewReader(content)
mrc := &MultiReadCloser{
Reader: reader,
}
// Read in chunks
buf1 := make([]byte, 4)
n1, err := mrc.Read(buf1)
if err != nil {
t.Fatalf("First Read() returned error: %v", err)
}
if n1 != 4 {
t.Errorf("First Read() returned %d bytes, expected 4", n1)
}
buf2 := make([]byte, 8)
n2, err := mrc.Read(buf2)
if err != nil {
t.Fatalf("Second Read() returned error: %v", err)
}
if n2 != 8 {
t.Errorf("Second Read() returned %d bytes, expected 8", n2)
}
// Verify content
combined := string(buf1) + string(buf2)
if combined != content[:12] {
t.Errorf("Combined reads returned %q, expected %q", combined, content[:12])
}
}
func TestMultiReadCloser_EOF(t *testing.T) {
content := "short"
reader := strings.NewReader(content)
mrc := &MultiReadCloser{
Reader: reader,
CloseFunc: func() error {
return nil
},
}
// Read all content
buf := make([]byte, len(content))
_, err := io.ReadFull(mrc, buf)
if err != nil {
t.Fatalf("ReadFull() returned error: %v", err)
}
// Try to read more - should get EOF
buf2 := make([]byte, 10)
n, err := mrc.Read(buf2)
if !errors.Is(err, io.EOF) {
t.Errorf("Read() after EOF returned error %v, expected io.EOF", err)
}
if n != 0 {
t.Errorf("Read() after EOF returned %d bytes, expected 0", n)
}
}
func TestMultiReadCloser_NilCloseFunc(t *testing.T) {
reader := strings.NewReader("test")
mrc := &MultiReadCloser{
Reader: reader,
}
// This should panic when Close() is called
defer func() {
if r := recover(); r == nil {
t.Errorf("Close() with nil CloseFunc should panic")
}
}()
mrc.Close()
}
func TestMultiReadCloser_EmptyReader(t *testing.T) {
reader := strings.NewReader("")
closeCalled := false
mrc := &MultiReadCloser{
Reader: reader,
CloseFunc: func() error {
closeCalled = true
return nil
},
}
// Try to read from empty reader
buf := make([]byte, 10)
n, err := mrc.Read(buf)
if !errors.Is(err, io.EOF) {
t.Errorf("Read() from empty reader returned error %v, expected io.EOF", err)
}
if n != 0 {
t.Errorf("Read() from empty reader returned %d bytes, expected 0", n)
}
// Close should still work
err = mrc.Close()
if err != nil {
t.Fatalf("Close() returned error: %v", err)
}
if !closeCalled {
t.Errorf("CloseFunc was not called")
}
}
func TestMultiReadCloser_MultipleCloses(t *testing.T) {
reader := strings.NewReader("test")
closeCount := 0
mrc := &MultiReadCloser{
Reader: reader,
CloseFunc: func() error {
closeCount++
return nil
},
}
// Close multiple times
err := mrc.Close()
if err != nil {
t.Fatalf("First Close() returned error: %v", err)
}
err = mrc.Close()
if err != nil {
t.Fatalf("Second Close() returned error: %v", err)
}
// Verify CloseFunc was called twice
if closeCount != 2 {
t.Errorf("CloseFunc was called %d times, expected 2", closeCount)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/ai_task.go | types/ai_task.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 types
import (
"encoding/json"
"github.com/harness/gitness/types/enum"
)
type AITask struct {
ID int64 `json:"id"`
Identifier string `json:"identifier"`
GitspaceConfigID int64 `json:"-"`
GitspaceInstanceID int64 `json:"-"`
GitspaceConfig *GitspaceConfig `json:"gitspace_config"`
InitialPrompt string `json:"initial_prompt"`
DisplayName string `json:"display_name"`
UserUID string `json:"user_uid"`
SpaceID int64 `json:"space_id"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
APIURL *string `json:"api_url,omitempty"`
AIAgent enum.AIAgent `json:"ai_agent"`
State enum.AITaskState `json:"state"`
Output *string `json:"output,omitempty"`
OutputMetadata json.RawMessage `json:"-"`
AIUsageMetric *AIUsageMetric `json:"ai_usage_metric,omitempty"`
ErrorMessage *string `json:"error_message,omitempty"`
}
type AIUsageMetric struct {
TotalCostUSD float64 `json:"total_cost_usd"`
DurationMs int64 `json:"duration_ms"`
TotalInputTokens int64 `json:"total_input_tokens"`
TotalOutputTokens int64 `json:"total_output_tokens"`
LLMModels []string `json:"llm_models"`
}
type AITaskFilter struct {
QueryFilter ListQueryFilter
SpaceID int64
UserIdentifier string
AIAgents []enum.AIAgent
States []enum.AITaskState
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/authz.go | types/authz.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 types
import "github.com/harness/gitness/types/enum"
// PermissionCheck represents a permission check.
type PermissionCheck struct {
Scope Scope
Resource Resource
Permission enum.Permission
}
// Resource represents the resource of a permission check.
// Note: Keep the name empty in case access is requested for all resources of that type.
type Resource struct {
Type enum.ResourceType
Identifier string
}
// Scope represents the scope of a permission check
// Notes:
// - In case the permission check is for resource REPO, keep repo empty (repo is resource, not scope)
// - In case the permission check is for resource SPACE, SpacePath is an ancestor of the space (space is
// resource, not scope)
// - Repo isn't use as of now (will be useful once we add access control for repo child resources, e.g. branches).
type Scope struct {
SpacePath string
Repo string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/devcontainer_feature_config.go | types/devcontainer_feature_config.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 types
import (
"fmt"
"slices"
"strconv"
"github.com/harness/gitness/types/enum"
)
//nolint:tagliatelle
type DevcontainerFeatureConfig struct {
ID string `json:"id,omitempty"`
Version string `json:"version,omitempty"`
Name string `json:"name,omitempty"`
Options *Options `json:"options,omitempty"`
DependsOn *Features `json:"dependsOn,omitempty"`
ContainerEnv map[string]string `json:"containerEnv,omitempty"`
Privileged bool `json:"privileged,omitempty"`
Init bool `json:"init,omitempty"`
CapAdd []string `json:"capAdd,omitempty"`
SecurityOpt []string `json:"securityOpt,omitempty"`
Entrypoint string `json:"entrypoint,omitempty"`
InstallsAfter []string `json:"installsAfter,omitempty"`
Mounts []*Mount `json:"mounts,omitempty"`
PostCreateCommand LifecycleCommand `json:"postCreateCommand"`
PostStartCommand LifecycleCommand `json:"postStartCommand"`
}
type Options map[string]*OptionDefinition
type OptionDefinition struct {
Type enum.FeatureOptionValueType `json:"type,omitempty"`
Proposals []string `json:"proposals,omitempty"`
Enum []string `json:"enum,omitempty"`
Default any `json:"default,omitempty"`
Description string `json:"description,omitempty"`
}
// ValidateValue checks if the value matches the type defined in the definition. For string types,
// it also checks if it is allowed ie it is present in the enum array for the option.
// Reference: https://containers.dev/implementors/features/#options-property
func (o *OptionDefinition) ValidateValue(optionValue any, optionKey string, featureSource string) (string, error) {
switch o.Type {
case enum.FeatureOptionValueTypeBoolean:
boolValue, ok := optionValue.(bool)
if ok {
return strconv.FormatBool(boolValue), nil
}
stringValue, ok := optionValue.(string)
if ok {
parsedBoolValue, err := strconv.ParseBool(stringValue)
if err == nil {
return strconv.FormatBool(parsedBoolValue), nil
}
}
return "", fmt.Errorf("error during resolving feature %s, option Id %s "+
"expects boolean, got %s ", featureSource, optionKey, optionValue)
case enum.FeatureOptionValueTypeString:
stringValue, ok := optionValue.(string)
if !ok {
return "", fmt.Errorf("error during resolving feature %s, option Id %s "+
"expects string, got %s ", featureSource, optionKey, optionValue)
}
if len(o.Enum) > 0 && !slices.Contains(o.Enum, stringValue) {
return "", fmt.Errorf("error during resolving feature %s, option value %s "+
"not allowed for Id %s ", featureSource, stringValue, optionKey)
}
return stringValue, nil
default:
return "", fmt.Errorf("unsupported option type %s", o.Type)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/branch.go | types/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 types
import "github.com/harness/gitness/git/sha"
type Branch struct {
Name string `json:"name"`
SHA sha.SHA `json:"sha"`
Commit *Commit `json:"commit,omitempty"`
}
type BranchTable struct {
Name string `json:"name"`
SHA sha.SHA `json:"-"`
CreatedBy int64 `json:"created_by"`
Created int64 `json:"created"`
UpdatedBy int64 `json:"updated_by"`
Updated int64 `json:"updated"`
LastCreatedPullReqID *int64 `json:"last_created_pull_req_id,omitempty"`
}
type BranchExtended struct {
Branch
IsDefault bool `json:"is_default"`
CheckSummary *CheckCountSummary `json:"check_summary,omitempty"`
Rules []RuleInfo `json:"rules,omitempty"`
PullRequests []*PullReq `json:"pull_requests,omitempty"`
CommitDivergence *CommitDivergence `json:"commit_divergence,omitempty"`
}
type CreateBranchOutput struct {
Branch
DryRunRulesOutput
}
type DeleteBranchOutput struct {
DryRunRulesOutput
}
// CommitDivergence contains the information of the count of converging commits between two refs.
type CommitDivergence struct {
// Ahead is the count of commits the 'From' ref is ahead of the 'To' ref.
Ahead int32 `json:"ahead"`
// Behind is the count of commits the 'From' ref is behind the 'To' ref.
Behind int32 `json:"behind"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/pullreq_activity_payload.go | types/pullreq_activity_payload.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 types
import (
"errors"
"fmt"
"github.com/harness/gitness/git/sha"
"github.com/harness/gitness/types/enum"
)
var (
// jsonRawMessageNullBytes represents the byte array that's equivalent to a nil json.RawMessage.
jsonRawMessageNullBytes = []byte("null")
// ErrNoPayload is returned in case the activity doesn't have any payload set.
ErrNoPayload = errors.New("activity has no payload")
)
// PullReqActivityPayload is an interface used to identify PR activity payload types.
// The approach is inspired by what protobuf is doing for oneof.
type PullReqActivityPayload interface {
// ActivityType returns the pr activity type the payload is meant for.
// NOTE: this allows us to do easy payload type verification without any kind of reflection.
ActivityType() enum.PullReqActivityType
}
// activityPayloadFactoryMethod is an alias for a function that creates a new PullReqActivityPayload.
// NOTE: this is used to create new instances for activities on the fly (to avoid reflection)
// NOTE: we could add new() to PullReqActivityPayload interface, but it shouldn't be the payloads' responsibility.
type activityPayloadFactoryMethod func() PullReqActivityPayload
// allPullReqActivityPayloads is a map that contains the payload factory methods for all activity types with payload.
var allPullReqActivityPayloads = func(
factoryMethods []activityPayloadFactoryMethod,
) map[enum.PullReqActivityType]activityPayloadFactoryMethod {
payloadMap := make(map[enum.PullReqActivityType]activityPayloadFactoryMethod)
for _, factoryMethod := range factoryMethods {
payloadMap[factoryMethod().ActivityType()] = factoryMethod
}
return payloadMap
}([]activityPayloadFactoryMethod{
func() PullReqActivityPayload { return PullRequestActivityPayloadComment{} },
func() PullReqActivityPayload { return &PullRequestActivityPayloadCodeComment{} },
func() PullReqActivityPayload { return &PullRequestActivityPayloadMerge{} },
func() PullReqActivityPayload { return &PullRequestActivityPayloadStateChange{} },
func() PullReqActivityPayload { return &PullRequestActivityPayloadTitleChange{} },
func() PullReqActivityPayload { return &PullRequestActivityPayloadReviewSubmit{} },
func() PullReqActivityPayload { return &PullRequestActivityPayloadBranchUpdate{} },
func() PullReqActivityPayload { return &PullRequestActivityPayloadBranchDelete{} },
func() PullReqActivityPayload { return &PullRequestActivityPayloadBranchRestore{} },
})
// newPayloadForActivity returns a new payload instance for the requested activity type.
func newPayloadForActivity(t enum.PullReqActivityType) (PullReqActivityPayload, error) {
payloadFactoryMethod, ok := allPullReqActivityPayloads[t]
if !ok {
return nil, fmt.Errorf("pr activity type '%s' doesn't have a payload", t)
}
return payloadFactoryMethod(), nil
}
type PullRequestActivityPayloadComment struct{}
func (a PullRequestActivityPayloadComment) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeComment
}
type PullRequestActivityPayloadCodeComment struct {
Title string `json:"title"`
Lines []string `json:"lines"`
LineStartNew bool `json:"line_start_new"`
LineEndNew bool `json:"line_end_new"`
}
func (a *PullRequestActivityPayloadCodeComment) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeCodeComment
}
type PullRequestActivityPayloadMerge struct {
MergeMethod enum.MergeMethod `json:"merge_method"`
MergeSHA string `json:"merge_sha"`
TargetSHA string `json:"target_sha"`
SourceSHA string `json:"source_sha"`
RulesBypassed bool `json:"rules_bypassed,omitempty"`
}
func (a *PullRequestActivityPayloadMerge) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeMerge
}
type PullRequestActivityPayloadStateChange struct {
Old enum.PullReqState `json:"old"`
New enum.PullReqState `json:"new"`
OldDraft bool `json:"old_draft"`
NewDraft bool `json:"new_draft"`
}
func (a *PullRequestActivityPayloadStateChange) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeStateChange
}
type PullRequestActivityPayloadTitleChange struct {
Old string `json:"old"`
New string `json:"new"`
}
func (a *PullRequestActivityPayloadTitleChange) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeTitleChange
}
type PullRequestActivityPayloadReviewSubmit struct {
CommitSHA string `json:"commit_sha"`
Decision enum.PullReqReviewDecision `json:"decision"`
}
func (a *PullRequestActivityPayloadReviewSubmit) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeReviewSubmit
}
type PullRequestActivityPayloadReviewerAdd struct {
PrincipalID int64 `json:"principal_id,omitempty"`
PrincipalIDs []int64 `json:"principal_ids,omitempty"`
ReviewerType enum.PullReqReviewerType `json:"reviewer_type"`
}
func (a *PullRequestActivityPayloadReviewerAdd) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeReviewerAdd
}
type PullRequestActivityPayloadUserGroupReviewerAdd struct {
UserGroupIDs []int64 `json:"user_group_ids,omitempty"`
ReviewerType enum.PullReqReviewerType `json:"reviewer_type"`
}
func (a *PullRequestActivityPayloadUserGroupReviewerAdd) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeUserGroupReviewerAdd
}
type PullRequestActivityPayloadReviewerDelete struct {
CommitSHA string `json:"commit_sha"`
Decision enum.PullReqReviewDecision `json:"decision"`
PrincipalID int64 `json:"principal_id"`
}
func (a *PullRequestActivityPayloadReviewerDelete) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeReviewerDelete
}
type PullRequestActivityPayloadUserGroupReviewerDelete struct {
UserGroupIDs []int64 `json:"user_group_ids"`
}
func (a *PullRequestActivityPayloadUserGroupReviewerDelete) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeUserGroupReviewerDelete
}
type PullRequestActivityPayloadBranchUpdate struct {
Old string `json:"old"`
New string `json:"new"`
Forced bool `json:"forced"`
CommitTitle string `json:"commit_title"`
}
func (a *PullRequestActivityPayloadBranchUpdate) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeBranchUpdate
}
type PullRequestActivityPayloadBranchDelete struct {
SHA string `json:"sha"`
}
func (a *PullRequestActivityPayloadBranchDelete) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeBranchDelete
}
type PullRequestActivityPayloadBranchRestore struct {
SHA string `json:"sha"`
}
func (a *PullRequestActivityPayloadBranchRestore) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeBranchRestore
}
type PullRequestActivityPayloadBranchChangeTarget struct {
Old string `json:"old"`
New string `json:"new"`
}
func (a *PullRequestActivityPayloadBranchChangeTarget) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeTargetBranchChange
}
type PullRequestActivityLabelBase struct {
Label string `json:"label"`
LabelColor enum.LabelColor `json:"label_color"`
LabelScope int64 `json:"label_scope"`
Value *string `json:"value,omitempty"`
ValueColor *enum.LabelColor `json:"value_color,omitempty"`
OldValue *string `json:"old_value,omitempty"`
OldValueColor *enum.LabelColor `json:"old_value_color,omitempty"`
}
type PullRequestActivityLabel struct {
PullRequestActivityLabelBase
Type enum.PullReqLabelActivityType `json:"type"`
}
func (a *PullRequestActivityLabel) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeLabelModify
}
type PullRequestActivityLabels struct {
Type enum.PullReqLabelActivityType `json:"type"`
Labels []*PullRequestActivityLabelBase `json:"labels"`
}
func (a *PullRequestActivityLabels) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeLabelModify
}
type PullRequestActivityPayloadNonUniqueMergeBase struct {
TargetSHA sha.SHA `json:"target_sha"`
SourceSHA sha.SHA `json:"source_sha"`
}
func (a *PullRequestActivityPayloadNonUniqueMergeBase) ActivityType() enum.PullReqActivityType {
return enum.PullReqActivityTypeNonUniqueMergeBase
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/jetbrains.go | types/jetbrains.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 types
import "github.com/harness/gitness/types/enum"
type JetBrainsIDEDownloadURLTemplates struct {
Version string
Amd64Sha string
Arm64Sha string
Amd64 string
Arm64 string
}
var JetBrainsIDEDownloadURLTemplateMap = map[enum.IDEType]JetBrainsIDEDownloadURLTemplates{
enum.IDETypeIntelliJ: {
// list of versions: https://www.jetbrains.com/idea/download/other.html
Version: "2024.3.1.1",
Amd64: "https://download.jetbrains.com/idea/ideaIU-%s.tar.gz",
Arm64: "https://download.jetbrains.com/idea/ideaIU-%s-aarch64.tar.gz",
},
enum.IDETypeGoland: {
// list of versions: https://www.jetbrains.com/go/download/other.html
Version: "2024.3.1",
Amd64: "https://download.jetbrains.com/go/goland-%s.tar.gz",
Arm64: "https://download.jetbrains.com/go/goland-%s-aarch64.tar.gz",
},
enum.IDETypePyCharm: {
// list of versions: https://www.jetbrains.com/pycharm/download/other.html
Version: "2024.3.1.1",
Amd64: "https://download.jetbrains.com/python/pycharm-professional-%s.tar.gz",
Arm64: "https://download.jetbrains.com/python/pycharm-professional-%s-aarch64.tar.gz",
},
enum.IDETypeWebStorm: {
// list of versions: https://www.jetbrains.com/webstorm/download/other.html
Version: "2024.3.1.1",
Amd64: "https://download.jetbrains.com/webstorm/WebStorm-%s.tar.gz",
Arm64: "https://download.jetbrains.com/webstorm/WebStorm-%s-aarch64.tar.gz",
},
enum.IDETypeCLion: {
// list of versions: https://www.jetbrains.com/clion/download/other.html
Version: "2024.3.1.1",
Amd64: "https://download.jetbrains.com/cpp/CLion-%s.tar.gz",
Arm64: "https://download.jetbrains.com/cpp/CLion-%s-aarch64.tar.gz",
},
enum.IDETypePHPStorm: {
// list of versions: https://www.jetbrains.com/phpstorm/download/other.html
Version: "2024.3.1.1",
Amd64: "https://download.jetbrains.com/webide/PhpStorm-%s.tar.gz",
Arm64: "https://download.jetbrains.com/webide/PhpStorm-%s-aarch64.tar.gz",
},
enum.IDETypeRubyMine: {
// list of versions: https://www.jetbrains.com/ruby/download/other.html
Version: "2024.3.1.1",
Amd64: "https://download.jetbrains.com/ruby/RubyMine-%s.tar.gz",
Arm64: "https://download.jetbrains.com/ruby/RubyMine-%s-aarch64.tar.gz",
},
enum.IDETypeRider: {
// list of versions: https://www.jetbrains.com/ruby/download/other.html
Version: "2024.3.3",
Amd64: "https://download.jetbrains.com/rider/JetBrains.Rider-%s.tar.gz",
Arm64: "https://download.jetbrains.com/rider/JetBrains.Rider-%s-aarch64.tar.gz",
},
}
type JetBrainsSpecs struct {
IDEType enum.IDEType
DownloadURls JetBrainsIDEDownloadURLTemplates
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/usergroup.go | types/usergroup.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 types defines common data structures.
package types
type UserGroup struct {
ID int64 `json:"id"`
Identifier string `json:"identifier"`
Name string `json:"name"`
Description string `json:"description"`
SpaceID int64 `json:"-"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
Users []string // Users are used by the code owners code
Scope int64 `json:"scope"`
}
type UserGroupInfo struct {
ID int64 `json:"id"`
Identifier string `json:"identifier"`
Name string `json:"name"`
Description string `json:"description"`
Scope int64 `json:"scope"`
}
func (u *UserGroup) ToUserGroupInfo() *UserGroupInfo {
return &UserGroupInfo{
ID: u.ID,
Identifier: u.Identifier,
Name: u.Name,
Description: u.Description,
Scope: u.Scope,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/connector.go | types/connector.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 types
import (
"github.com/harness/gitness/types/enum"
)
type Connector struct {
ID int64 `json:"-"`
Description string `json:"description"`
SpaceID int64 `json:"space_id"`
Identifier string `json:"identifier"`
CreatedBy int64 `json:"created_by"`
Type enum.ConnectorType `json:"type"`
LastTestAttempt int64 `json:"last_test_attempt"`
LastTestErrorMsg string `json:"last_test_error_msg"`
LastTestStatus enum.ConnectorStatus `json:"last_test_status"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
Version int64 `json:"-"`
// Pointers to connector specific data
ConnectorConfig
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/step.go | types/step.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 types
import (
"encoding/json"
"fmt"
"github.com/harness/gitness/types/enum"
)
type Step struct {
ID int64 `json:"-"`
StageID int64 `json:"-"`
Number int64 `json:"number"`
Name string `json:"name"`
Status enum.CIStatus `json:"status"`
Error string `json:"error,omitempty"`
ErrIgnore bool `json:"errignore,omitempty"`
ExitCode int `json:"exit_code"`
Started int64 `json:"started,omitempty"`
Stopped int64 `json:"stopped,omitempty"`
Version int64 `json:"-" db:"step_version"`
DependsOn []string `json:"depends_on,omitempty"`
Image string `json:"image,omitempty"`
Detached bool `json:"detached"`
Schema string `json:"schema,omitempty"`
}
// Pretty print a step.
func (s Step) String() string {
// Convert the Step struct to JSON
jsonStr, err := json.MarshalIndent(s, "", " ")
if err != nil {
return fmt.Sprintf("Error converting to JSON: %v", err)
}
return string(jsonStr)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/gitspace_event.go | types/gitspace_event.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import "github.com/harness/gitness/types/enum"
type GitspaceEvent struct {
ID int64 `json:"-"`
Event enum.GitspaceEventType `json:"event,omitempty"`
EntityID int64 `json:"-"`
QueryKey string `json:"query_key,omitempty"`
EntityType enum.GitspaceEntityType `json:"entity_type,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
Created int64 `json:"created,omitempty"`
}
type GitspaceEventResponse struct {
GitspaceEvent
EventTime string `json:"event_time,omitempty"`
Message string `json:"message,omitempty"`
}
type GitspaceEventFilter struct {
Pagination
QueryKey string
EntityID int64
EntityType enum.GitspaceEntityType
SkipEvents []enum.GitspaceEventType // not include events
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/mask_secret.go | types/mask_secret.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 types
import (
"crypto/sha256"
"encoding/json"
"fmt"
)
const maxTruncatedLen = 8
// MaskSecret is a wrapper to store decrypted secrets in memory. This is help to prevent them
// from getting prints in logs and fmt.
type MaskSecret struct {
value string
hashedValue string
}
func NewMaskSecret(val string) MaskSecret {
hash := sha256.New()
hash.Write([]byte(val))
hashedValueStr := fmt.Sprintf("%x", hash.Sum(nil))
return MaskSecret{
value: val,
hashedValue: hashedValueStr[:maxTruncatedLen],
}
}
// Value returns the unmasked value of the MaskSecret.
// Use cautiously to avoid exposing sensitive data.
func (s MaskSecret) Value() string {
return s.value
}
func (s MaskSecret) String() string {
if s.hashedValue == "" && s.value != "" {
// this case can arise when MarkSecret is created by UnmarshalJSON func where we do not
// use NewMaskSecret constructor.
hash := sha256.New()
hash.Write([]byte(s.value))
hashedValueStr := fmt.Sprintf("%x", hash.Sum(nil))
s.hashedValue = hashedValueStr[:maxTruncatedLen]
}
return s.hashedValue
}
func (s MaskSecret) MarshalJSON() ([]byte, error) {
return json.Marshal(s.value)
}
// UnmarshalJSON needs pointer receiver as it modify the receiver.
func (s *MaskSecret) UnmarshalJSON(data []byte) error {
var input string
if err := json.Unmarshal(data, &input); err != nil {
return err
}
s.value = input
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/gitspace.go | types/gitspace.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"fmt"
"github.com/harness/gitness/types/enum"
)
const emptyGitspaceInstanceState = ""
type GitspaceConfig struct {
ID int64 `json:"-"`
Identifier string `json:"identifier"`
Name string `json:"name"`
IDE enum.IDEType `json:"ide"`
State enum.GitspaceStateType `json:"state"`
SpaceID int64 `json:"-"`
IsDeleted bool `json:"-"`
IsMarkedForDeletion bool `json:"-"`
IsMarkedForReset bool `json:"is_marked_for_reset"`
IsMarkedForInfraReset bool `json:"is_marked_for_infra_reset"`
GitspaceInstance *GitspaceInstance `json:"instance"`
SpacePath string `json:"space_path"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
SSHTokenIdentifier string `json:"ssh_token_identifier"`
InfraProviderResource InfraProviderResource `json:"resource"`
LogKey string `json:"log_key"`
InitializeLogKey string `json:"initialize_log_key"`
AIAgents []enum.AIAgent `json:"ai_agents,omitempty"`
AIAuth map[enum.AIAgent]AIAgentAuth `json:"-"`
CodeRepo
GitspaceUser
Connectors []PlatformConnector `json:"-"`
}
type CodeRepo struct {
URL string `json:"code_repo_url"`
Ref *string `json:"code_repo_ref"`
Type enum.GitspaceCodeRepoType `json:"code_repo_type"`
Branch string `json:"branch"`
BranchURL string `json:"branch_url,omitempty"`
DevcontainerPath *string `json:"devcontainer_path,omitempty"`
IsPrivate bool `json:"code_repo_is_private"`
AuthType string `json:"-"`
AuthID string `json:"-"`
}
type GitspaceUser struct {
ID *int64 `json:"-"`
Identifier string `json:"user_id"`
Email string `json:"user_email"`
DisplayName string `json:"user_display_name"`
}
type GitspaceInstance struct {
ID int64 `json:"-"`
GitSpaceConfigID int64 `json:"-"`
Identifier string `json:"identifier"`
URL *string `json:"url,omitempty"`
SSHCommand *string `json:"ssh_command,omitempty"`
PluginURL *string `json:"plugin_url,omitempty"`
State enum.GitspaceInstanceStateType `json:"state"`
UserID string `json:"-"`
ResourceUsage *string `json:"resource_usage"`
LastUsed *int64 `json:"last_used,omitempty"`
TotalTimeUsed int64 `json:"total_time_used"`
AccessKey *string `json:"access_key,omitempty"`
AccessType enum.GitspaceAccessType `json:"access_type"`
AccessKeyRef *string `json:"access_key_ref"`
MachineUser *string `json:"machine_user,omitempty"`
SpacePath string `json:"space_path"`
SpaceID int64 `json:"-"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
LastHeartbeat *int64 `json:"last_heartbeat,omitempty"`
ActiveTimeStarted *int64 `json:"active_time_started,omitempty"`
ActiveTimeEnded *int64 `json:"active_time_ended,omitempty"`
HasGitChanges *bool `json:"has_git_changes,omitempty"`
ErrorMessage *string `json:"error_message,omitempty"`
}
type GitspaceFilter struct {
QueryFilter ListQueryFilter
Sort enum.GitspaceSort `json:"sort"`
Order enum.Order `json:"order"`
Owner enum.GitspaceOwner
GitspaceFilterStates []enum.GitspaceFilterState
CodeRepoTypes []enum.GitspaceCodeRepoType
Deleted *bool // not nil when we want to add this filter
MarkedForDeletion *bool // not nil when we want to add this filter
GitspaceInstanceFilter
ScopeFilter
}
type ScopeFilter struct {
// each org will be of the format "orgID"
Orgs []string
// each project will be of the format "orgID/projectID"
Projects []string
}
type GitspaceInstanceFilter struct {
UserIdentifier string
LastUsedBefore int64
LastHeartBeatBefore int64
LastUpdatedBefore int64
States []enum.GitspaceInstanceStateType
SpaceIDs []int64
// AllowAllSpaces is enabled for cde-manager jobs to list all gitspaces
AllowAllSpaces bool
Limit int
}
func (g *GitspaceInstance) GetGitspaceState() (enum.GitspaceStateType, error) {
if g == nil {
return enum.GitspaceStateError, fmt.Errorf("GitspaceInstance is nil")
}
instanceState := g.State
//nolint:exhaustive
switch instanceState {
case enum.GitspaceInstanceStateRunning:
return enum.GitspaceStateRunning, nil
case enum.GitspaceInstanceStateStopped:
return enum.GitspaceStateStopped, nil
case emptyGitspaceInstanceState,
enum.GitspaceInstanceStateUninitialized,
enum.GitspaceInstanceStateDeleted,
enum.GitspaceInstanceStateCleaned:
return enum.GitspaceStateUninitialized, nil
case enum.GitspaceInstanceStateError,
enum.GitspaceInstanceStateUnknown:
return enum.GitspaceStateError, nil
case enum.GitspaceInstanceStateStarting:
return enum.GitspaceStateStarting, nil
case enum.GitspaceInstanceStateStopping:
return enum.GitspaceStateStopping, nil
case enum.GitSpaceInstanceStateCleaning,
enum.GitSpaceInstanceStateResetting:
return enum.GitSpaceStateCleaning, nil
default:
return enum.GitspaceStateError, fmt.Errorf("unsupported gitspace instance state %s", string(instanceState))
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/connector_test_response.go | types/connector_test_response.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 types
import "github.com/harness/gitness/types/enum"
type ConnectorTestResponse struct {
Status enum.ConnectorStatus `json:"status"`
ErrorMsg string `json:"error_msg,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/user.go | types/user.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package types defines common data structures.
package types
import (
"github.com/harness/gitness/types/enum"
)
type (
// User is a principal representing an end user.
User struct {
// Fields from Principal
ID int64 `db:"principal_id" json:"id"`
UID string `db:"principal_uid" json:"uid"`
Email string `db:"principal_email" json:"email"`
DisplayName string `db:"principal_display_name" json:"display_name"`
Admin bool `db:"principal_admin" json:"admin"`
Blocked bool `db:"principal_blocked" json:"blocked"`
Salt string `db:"principal_salt" json:"-"`
Created int64 `db:"principal_created" json:"created"`
Updated int64 `db:"principal_updated" json:"updated"`
// User specific fields
Password string `db:"principal_user_password" json:"-"`
}
// UserInput store user account details used to
// create or update a user.
UserInput struct {
Email *string `json:"email"`
Password *string `json:"password"`
Name *string `json:"name"`
Admin *bool `json:"admin"`
}
// UserFilter stores user query parameters.
UserFilter struct {
Page int `json:"page"`
Size int `json:"size"`
Sort enum.UserAttr `json:"sort"`
Order enum.Order `json:"order"`
Admin bool `json:"admin"`
}
)
func (u *User) ToPrincipal() *Principal {
return &Principal{
ID: u.ID,
UID: u.UID,
Email: u.Email,
Type: enum.PrincipalTypeUser,
DisplayName: u.DisplayName,
Admin: u.Admin,
Blocked: u.Blocked,
Salt: u.Salt,
Created: u.Created,
Updated: u.Updated,
}
}
func (u *User) ToPrincipalInfo() *PrincipalInfo {
return u.ToPrincipal().ToPrincipalInfo()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/gitspace_run_arg.go | types/gitspace_run_arg.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 types
import (
"strings"
)
type RunArg string
const (
RunArgAddHost = RunArg("--add-host")
RunArgAnnotation = RunArg("--annotation")
RunArgBlkioWeight = RunArg("--blkio-weight")
RunArgCapDrop = RunArg("--cap-drop")
RunArgCgroupParent = RunArg("--cgroup-parent")
RunArgCgroupns = RunArg("--cgroupns")
RunArgCPUCount = RunArg("--cpu-count")
RunArgCPUPercent = RunArg("--cpu-percent")
RunArgCPUPeriod = RunArg("--cpu-period")
RunArgCPUQuota = RunArg("--cpu-quota")
RunArgCPURtPeriod = RunArg("--cpu-rt-period")
RunArgCPURtRuntime = RunArg("--cpu-rt-runtime")
RunArgCPUShares = RunArg("--cpu-shares")
RunArgCpus = RunArg("--cpus")
RunArgCpusetCpus = RunArg("--cpuset-cpus")
RunArgCpusetMems = RunArg("--cpuset-mems")
RunArgDNS = RunArg("--dns")
RunArgDNSOption = RunArg("--dns-option")
RunArgDNSSearch = RunArg("--dns-search")
RunArgDomainname = RunArg("--domainname")
RunArgEntrypoint = RunArg("--entrypoint")
RunArgEnv = RunArg("--env")
RunArgHealthCmd = RunArg("--health-cmd")
RunArgHealthInterval = RunArg("--health-interval")
RunArgHealthRetries = RunArg("--health-retries")
RunArgHealthStartInterval = RunArg("--health-start-interval")
RunArgHealthStartPeriod = RunArg("--health-start-period")
RunArgHealthTimeout = RunArg("--health-timeout")
RunArgHostname = RunArg("--hostname")
RunArgInit = RunArg("--init")
RunArgIoMaxbandwidth = RunArg("--io-maxbandwidth")
RunArgIoMaxiops = RunArg("--io-maxiops")
RunArgIpc = RunArg("--ipc")
RunArgIsolation = RunArg("--isolation")
RunArgKernelMemory = RunArg("--kernel-memory")
RunArgLabel = RunArg("--label")
RunArgLink = RunArg("--link")
RunArgMacAddress = RunArg("--mac-address")
RunArgMemory = RunArg("--memory")
RunArgMemoryReservation = RunArg("--memory-reservation")
RunArgMemorySwap = RunArg("--memory-swap")
RunArgMemorySwappiness = RunArg("--memory-swappiness")
RunArgNetwork = RunArg("--network")
RunArgNoHealthcheck = RunArg("--no-healthcheck")
RunArgOomKillDisable = RunArg("--oom-kill-disable")
RunArgOomScoreAdj = RunArg("--oom-score-adj")
RunArgPid = RunArg("--pid")
RunArgPidsLimit = RunArg("--pids-limit")
RunArgPlatform = RunArg("--platform")
RunArgPull = RunArg("--pull")
RunArgRestart = RunArg("--restart")
RunArgRm = RunArg("--rm")
RunArgRuntime = RunArg("--runtime")
RunArgSecurityOpt = RunArg("--security-opt")
RunArgShmSize = RunArg("--shm-size")
RunArgStopSignal = RunArg("--stop-signal")
RunArgStopTimeout = RunArg("--stop-timeout")
RunArgStorageOpt = RunArg("--storage-opt")
RunArgSysctl = RunArg("--sysctl")
RunArgUlimit = RunArg("--ulimit")
RunArgUser = RunArg("--user")
RunArgPrivileged = RunArg("--privileged")
RunArgCapAdd = RunArg("--cap-add")
RunArgMount = RunArg("--mount")
)
type RunArgDefinition struct {
Name RunArg `yaml:"name"`
ShortHand RunArg `yaml:"short_hand"`
Supported bool `yaml:"supported"`
BlockedValues map[string]bool `yaml:"blocked_values"`
AllowedValues map[string]bool `yaml:"allowed_values"`
AllowMultipleOccurences bool `yaml:"allow_multiple_occurrences"`
}
type RunArgValue struct {
Name RunArg
Values []string
}
func (c *RunArgValue) String() string {
return strings.Join(c.Values, ", ")
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/rule.go | types/rule.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"bytes"
"encoding/json"
"fmt"
"github.com/harness/gitness/types/enum"
"gopkg.in/yaml.v3"
)
type Rule struct {
ID int64 `json:"-"`
Version int64 `json:"-"`
CreatedBy int64 `json:"-"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
RepoID *int64 `json:"-"`
SpaceID *int64 `json:"-"`
Identifier string `json:"identifier"`
Description string `json:"description"`
Type enum.RuleType `json:"type"`
State enum.RuleState `json:"state"`
Pattern json.RawMessage `json:"pattern"`
RepoTarget json.RawMessage `json:"repo_target"`
Definition json.RawMessage `json:"definition"`
CreatedByInfo PrincipalInfo `json:"created_by"`
Users map[int64]*PrincipalInfo `json:"users"`
UserGroups map[int64]*UserGroupInfo `json:"user_groups"`
Repositories map[int64]*RepositoryCore `json:"repositories"`
// scope 0 indicates repo; scope > 0 indicates space depth level
Scope int64 `json:"scope"`
}
// TODO [CODE-1363]: remove after identifier migration.
func (r Rule) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias Rule
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(r),
UID: r.Identifier,
})
}
func (r Rule) MarshalYAML() (any, error) {
// yaml cannot marshal json.RawMessage
pattern := make(map[string]any)
err := yaml.Unmarshal(r.Pattern, pattern)
if err != nil {
return nil, err
}
definition := make(map[string]any)
err = yaml.Unmarshal(r.Definition, definition)
if err != nil {
return nil, err
}
return map[string]any{
"id": r.ID,
"created": r.Created,
"updated": r.Updated,
"created_by": r.CreatedBy,
"identifier": r.Identifier,
"description": r.Description,
"type": r.Type,
"state": r.State,
"pattern": pattern,
"definition": definition,
}, nil
}
// Clone makes deep copy of the rule object.
func (r Rule) Clone() Rule {
var repoID *int64
var spaceID *int64
if r.RepoID != nil {
id := *r.RepoID
repoID = &id
}
if r.SpaceID != nil {
id := *r.SpaceID
spaceID = &id
}
r.RepoID = repoID
r.SpaceID = spaceID
pattern := make(json.RawMessage, len(r.Pattern))
copy(pattern, r.Pattern)
r.Pattern = pattern
definition := make(json.RawMessage, len(r.Definition))
copy(definition, r.Definition)
r.Definition = definition
users := make(map[int64]*PrincipalInfo, len(r.Users))
for key, value := range r.Users {
cloned := *value
users[key] = &cloned
}
r.Users = users
return r
}
func (r *Rule) IsEqual(rule *Rule) bool {
return r.Identifier == rule.Identifier && r.State == rule.State &&
r.Description == rule.Description && bytes.Equal(r.Pattern, rule.Pattern) &&
bytes.Equal(r.RepoTarget, rule.RepoTarget) &&
bytes.Equal(r.Definition, rule.Definition)
}
type RuleFilter struct {
ListQueryFilter
States []enum.RuleState
Types []enum.RuleType `json:"types"`
Sort enum.RuleSort `json:"sort"`
Order enum.Order `json:"order"`
}
// Violation represents a single violation.
type Violation struct {
Code string `json:"code"`
Message string `json:"message"`
Params []any `json:"params"`
}
// RuleViolations holds several violations of a rule.
type RuleViolations struct {
Rule RuleInfo `json:"rule"`
Bypassable bool `json:"bypassable"`
Bypassed bool `json:"bypassed"`
Violations []Violation `json:"violations"`
}
func (violations *RuleViolations) Add(code, message string) {
violations.Violations = append(violations.Violations, Violation{
Code: code,
Message: message,
Params: nil,
})
}
func (violations *RuleViolations) Addf(code, format string, params ...any) {
violations.Violations = append(violations.Violations, Violation{
Code: code,
Message: fmt.Sprintf(format, params...),
Params: params,
})
}
func (violations *RuleViolations) IsCritical() bool {
return violations.Rule.State == enum.RuleStateActive && len(violations.Violations) > 0 && !violations.Bypassed
}
func (violations *RuleViolations) IsBypassed() bool {
return violations.Rule.State == enum.RuleStateActive && len(violations.Violations) > 0 && violations.Bypassed
}
// RuleInfo holds basic info about a rule that is used to describe the rule in RuleViolations.
type RuleInfo struct {
SpacePath string `json:"space_path,omitempty"`
RepoPath string `json:"repo_path,omitempty"`
ID int64 `json:"-"`
Identifier string `json:"identifier"`
Type enum.RuleType `json:"type"`
State enum.RuleState `json:"state"`
}
// TODO [CODE-1363]: remove after identifier migration.
func (r RuleInfo) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias RuleInfo
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(r),
UID: r.Identifier,
})
}
type RuleInfoInternal struct {
RuleInfo
RepoTarget json.RawMessage
Pattern json.RawMessage
Definition json.RawMessage
}
type RulesViolations struct {
Message string `json:"message"`
Violations []RuleViolations `json:"violations"`
}
type DryRunRulesOutput struct {
DryRunRules bool `json:"dry_run_rules,omitempty"`
RuleViolations []RuleViolations `json:"rule_violations,omitempty"`
}
type RuleParentInfo struct {
Type enum.RuleParent
ID int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/template.go | types/template.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 types
import (
"encoding/json"
"github.com/harness/gitness/types/enum"
)
type Template struct {
ID int64 `db:"template_id" json:"-"`
Description string `db:"template_description" json:"description"`
Type enum.ResolverType `db:"template_type" json:"type"`
SpaceID int64 `db:"template_space_id" json:"space_id"`
Identifier string `db:"template_uid" json:"identifier"`
Data string `db:"template_data" json:"data"`
Created int64 `db:"template_created" json:"created"`
Updated int64 `db:"template_updated" json:"updated"`
Version int64 `db:"template_version" json:"-"`
}
// TODO [CODE-1363]: remove after identifier migration.
func (t Template) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias Template
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(t),
UID: t.Identifier,
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/plugin.go | types/plugin.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 types
import "encoding/json"
// Plugin represents a Harness plugin. It has an associated template stored
// in the spec field. The spec is used by the UI to provide a smart visual
// editor for adding plugins to YAML schema.
type Plugin struct {
Identifier string `db:"plugin_uid" json:"identifier"`
Description string `db:"plugin_description" json:"description"`
// Currently we only support step level plugins but more can be added in the future.
Type string `db:"plugin_type" json:"type"`
Version string `db:"plugin_version" json:"version"`
Logo string `db:"plugin_logo" json:"logo"`
// Spec is a YAML template to be used for the plugin.
Spec string `db:"plugin_spec" json:"spec"`
}
// Matches checks whether two plugins are identical.
// We can use reflection here, this is just easier to add on to
// when needed.
func (p *Plugin) Matches(v *Plugin) bool {
if p.Identifier != v.Identifier {
return false
}
if p.Description != v.Description {
return false
}
if p.Spec != v.Spec {
return false
}
if p.Version != v.Version {
return false
}
if p.Logo != v.Logo {
return false
}
return true
}
// TODO [CODE-1363]: remove after identifier migration.
func (p Plugin) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias Plugin
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(p),
UID: p.Identifier,
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/pipeline.go | types/pipeline.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 types
import "encoding/json"
type Pipeline struct {
ID int64 `db:"pipeline_id" json:"id"`
Description string `db:"pipeline_description" json:"description"`
Identifier string `db:"pipeline_uid" json:"identifier"`
Disabled bool `db:"pipeline_disabled" json:"disabled"`
CreatedBy int64 `db:"pipeline_created_by" json:"created_by"`
// Seq is the last execution number for this pipeline
Seq int64 `db:"pipeline_seq" json:"seq"`
RepoID int64 `db:"pipeline_repo_id" json:"repo_id"`
DefaultBranch string `db:"pipeline_default_branch" json:"default_branch"`
ConfigPath string `db:"pipeline_config_path" json:"config_path"`
Created int64 `db:"pipeline_created" json:"created"`
// Execution contains information about the latest execution if available
Execution *Execution `db:"-" json:"execution,omitempty"`
LastExecutions []*ExecutionInfo `db:"-" json:"last_executions,omitempty"`
Updated int64 `db:"pipeline_updated" json:"updated"`
Version int64 `db:"pipeline_version" json:"-"`
// Repo specific information not stored with pipelines
RepoUID string `db:"-" json:"repo_uid,omitempty"`
}
// TODO [CODE-1363]: remove after identifier migration.
func (s Pipeline) MarshalJSON() ([]byte, error) {
// alias allows us to embed the original object while avoiding an infinite loop of marshaling.
type alias Pipeline
return json.Marshal(&struct {
alias
UID string `json:"uid"`
}{
alias: (alias)(s),
UID: s.Identifier,
})
}
type ListPipelinesFilter struct {
ListQueryFilter
Latest bool
LastExecutions int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/infra_provisioned.go | types/infra_provisioned.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 types
import "github.com/harness/gitness/types/enum"
type InfraProvisioned struct {
ID int64
GitspaceInstanceID int64
InfraProviderType enum.InfraProviderType
InfraProviderResourceID int64
SpaceID int64
Created int64
Updated int64
ResponseMetadata *string
InputParams string
InfraStatus enum.InfraStatus
ServerHostIP string
ServerHostPort string
ProxyHost string
ProxyPort int32
GatewayHost string
}
type InfraProvisionedGatewayView struct {
GitspaceInstanceIdentifier string
SpaceID int64
ServerHostIP string
ServerHostPort string
Infrastructure *string
}
type InfraProvisionedUpdateGatewayRequest struct {
GitspaceInstanceIdentifier string `json:"gitspace_id"`
SpaceID int64 `json:"space_id"`
GatewayHost string `json:"gateway_host"`
GatewayPort int32 `json:"gateway_port"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/principal.go | types/principal.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package types defines common data structures.
package types
import (
"github.com/harness/gitness/types/enum"
)
// AnonymousPrincipalUID is an internal UID for anonymous principals.
const AnonymousPrincipalUID = "anonymous"
// Principal represents the identity of an acting entity (User, ServiceAccount, Service).
type Principal struct {
// TODO: int64 ID doesn't match DB
ID int64 `db:"principal_id" json:"id"`
UID string `db:"principal_uid" json:"uid"`
Email string `db:"principal_email" json:"email"`
Type enum.PrincipalType `db:"principal_type" json:"type"`
DisplayName string `db:"principal_display_name" json:"display_name"`
Admin bool `db:"principal_admin" json:"admin"`
// Should be part of principal or not?
Blocked bool `db:"principal_blocked" json:"blocked"`
Salt string `db:"principal_salt" json:"-"`
// Other info
Created int64 `db:"principal_created" json:"created"`
Updated int64 `db:"principal_updated" json:"updated"`
}
func (p *Principal) IsAnonymous() bool {
return p.UID == AnonymousPrincipalUID
}
func (p *Principal) ToPrincipalInfo() *PrincipalInfo {
return &PrincipalInfo{
ID: p.ID,
UID: p.UID,
DisplayName: p.DisplayName,
Email: p.Email,
Type: p.Type,
Created: p.Created,
Updated: p.Updated,
}
}
// PrincipalInfo is a compressed representation of a principal we return as part of non-principal APIs.
type PrincipalInfo struct {
ID int64 `json:"id"`
UID string `json:"uid"`
DisplayName string `json:"display_name"`
Email string `json:"email"`
Type enum.PrincipalType `json:"type"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
}
func (p *PrincipalInfo) Identifier() int64 {
return p.ID
}
type PrincipalFilter struct {
Page int `json:"page"`
Size int `json:"size"`
Query string `json:"query"`
Types []enum.PrincipalType `json:"types"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/pullreq_activity.go | types/pullreq_activity.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 types
import (
"bytes"
"encoding/json"
"fmt"
"github.com/harness/gitness/types/enum"
)
// PullReqActivity represents a pull request activity.
type PullReqActivity struct {
ID int64 `json:"id"`
Version int64 `json:"-"` // not returned, it's an internal field
CreatedBy int64 `json:"-"` // not returned, because the author info is in the Author field
Created int64 `json:"created"`
Updated int64 `json:"updated"` // we need updated to determine the latest version reliably.
Edited int64 `json:"edited"`
Deleted *int64 `json:"deleted,omitempty"`
ParentID *int64 `json:"parent_id"`
RepoID int64 `json:"repo_id"`
PullReqID int64 `json:"pullreq_id"`
Order int64 `json:"order"`
SubOrder int64 `json:"sub_order"`
ReplySeq int64 `json:"-"` // not returned, because it's a server's internal field
Type enum.PullReqActivityType `json:"type"`
Kind enum.PullReqActivityKind `json:"kind"`
Text string `json:"text"`
PayloadRaw json.RawMessage `json:"payload"`
Metadata *PullReqActivityMetadata `json:"metadata,omitempty"`
ResolvedBy *int64 `json:"-"` // not returned, because the resolver info is in the Resolver field
Resolved *int64 `json:"resolved,omitempty"`
Author PrincipalInfo `json:"author"`
Resolver *PrincipalInfo `json:"resolver,omitempty"`
CodeComment *CodeCommentFields `json:"code_comment,omitempty"`
// used only in response
Mentions map[int64]*PrincipalInfo `json:"mentions,omitempty"`
GroupMentions map[int64]*UserGroupInfo `json:"user_group_mentions,omitempty"`
}
func (a *PullReqActivity) IsValidCodeComment() bool {
return a.Type == enum.PullReqActivityTypeCodeComment &&
a.Kind == enum.PullReqActivityKindChangeComment &&
a.CodeComment != nil
}
func (a *PullReqActivity) AsCodeComment() *CodeComment {
if !a.IsValidCodeComment() {
return &CodeComment{}
}
return &CodeComment{
ID: a.ID,
Version: a.Version,
Updated: a.Updated,
CodeCommentFields: CodeCommentFields{
Outdated: a.CodeComment.Outdated,
MergeBaseSHA: a.CodeComment.MergeBaseSHA,
SourceSHA: a.CodeComment.SourceSHA,
Path: a.CodeComment.Path,
LineNew: a.CodeComment.LineNew,
SpanNew: a.CodeComment.SpanNew,
LineOld: a.CodeComment.LineOld,
SpanOld: a.CodeComment.SpanOld,
},
}
}
func (a *PullReqActivity) IsReplyable() bool {
return (a.Type == enum.PullReqActivityTypeComment || a.Type == enum.PullReqActivityTypeCodeComment) &&
a.SubOrder == 0
}
func (a *PullReqActivity) IsReply() bool {
return a.SubOrder > 0
}
// IsBlocking returns true if the pull request activity (comment/code-comment) is blocking the pull request merge.
func (a *PullReqActivity) IsBlocking() bool {
return a.SubOrder == 0 && a.Resolved == nil && a.Deleted == nil && a.Kind != enum.PullReqActivityKindSystem
}
// SetPayload sets the payload and verifies it's of correct type for the activity.
func (a *PullReqActivity) SetPayload(payload PullReqActivityPayload) error {
if payload == nil {
a.PayloadRaw = json.RawMessage(nil)
return nil
}
if payload.ActivityType() != a.Type {
return fmt.Errorf("wrong payload type %T for activity %s, payload is for %s",
payload, a.Type, payload.ActivityType())
}
var err error
if a.PayloadRaw, err = json.Marshal(payload); err != nil {
return fmt.Errorf("failed to marshal payload: %w", err)
}
return nil
}
// GetPayload returns the payload of the activity.
// An error is returned in case there's an issue retrieving the payload from its raw value.
// NOTE: To ensure rawValue gets changed always use SetPayload() with the updated payload.
func (a *PullReqActivity) GetPayload() (PullReqActivityPayload, error) {
// jsonMessage could also contain "null" - we still want to return ErrNoPayload in that case
if a.PayloadRaw == nil ||
bytes.Equal(a.PayloadRaw, jsonRawMessageNullBytes) {
return nil, ErrNoPayload
}
payload, err := newPayloadForActivity(a.Type)
if err != nil {
return nil, fmt.Errorf("failed to create new payload: %w", err)
}
if err = json.Unmarshal(a.PayloadRaw, payload); err != nil {
return nil, fmt.Errorf("failed to unmarshal payload: %w", err)
}
return payload, nil
}
// UpdateMetadata updates the metadata with the provided options.
func (a *PullReqActivity) UpdateMetadata(updates ...PullReqActivityMetadataUpdate) {
if a.Metadata == nil {
a.Metadata = &PullReqActivityMetadata{}
}
for _, update := range updates {
update.apply(a.Metadata)
}
if a.Metadata.IsEmpty() {
a.Metadata = nil
}
}
// PullReqActivityFilter stores pull request activity query parameters.
type PullReqActivityFilter struct {
After int64 `json:"after"`
Before int64 `json:"before"`
Limit int `json:"limit"`
Types []enum.PullReqActivityType `json:"type"`
Kinds []enum.PullReqActivityKind `json:"kind"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/service_account.go | types/service_account.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 types defines common data structures.
package types
import "github.com/harness/gitness/types/enum"
type (
// ServiceAccount is a principal representing a service account.
ServiceAccount struct {
// Fields from Principal (without admin, as it's never an admin)
ID int64 `db:"principal_id" json:"id"`
UID string `db:"principal_uid" json:"uid"`
Email string `db:"principal_email" json:"email"`
DisplayName string `db:"principal_display_name" json:"display_name"`
Admin bool `db:"principal_admin" json:"admin"`
Blocked bool `db:"principal_blocked" json:"blocked"`
Salt string `db:"principal_salt" json:"-"`
Created int64 `db:"principal_created" json:"created"`
Updated int64 `db:"principal_updated" json:"updated"`
// ServiceAccount specific fields
ParentType enum.ParentResourceType `db:"principal_sa_parent_type" json:"parent_type"`
ParentID int64 `db:"principal_sa_parent_id" json:"parent_id"`
}
// ServiceAccountInput store details used to
// create or update a service account.
ServiceAccountInput struct {
DisplayName *string `json:"display_name"`
ParentType *enum.ParentResourceType `json:"parent_type"`
ParentID *int64 `json:"parent_id"`
}
ServiceAccountInfo struct {
PrincipalInfo
ParentType enum.ParentResourceType `json:"parent_type"`
ParentID int64 `json:"parent_id"`
}
)
func (s *ServiceAccount) ToPrincipal() *Principal {
return &Principal{
ID: s.ID,
UID: s.UID,
Email: s.Email,
Type: enum.PrincipalTypeServiceAccount,
DisplayName: s.DisplayName,
Admin: s.Admin,
Blocked: s.Blocked,
Salt: s.Salt,
Created: s.Created,
Updated: s.Updated,
}
}
func (s *ServiceAccount) ToPrincipalInfo() *PrincipalInfo {
return s.ToPrincipal().ToPrincipalInfo()
}
func (s *ServiceAccount) ToServiceAccountInfo() *ServiceAccountInfo {
return &ServiceAccountInfo{
PrincipalInfo: *s.ToPrincipalInfo(),
ParentType: s.ParentType,
ParentID: s.ParentID,
}
}
type ServiceAccountParentInfo struct {
Type enum.ParentResourceType `json:"type"`
ID int64 `json:"id"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/common.go | types/common.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"strings"
"unicode"
"unicode/utf8"
"github.com/harness/gitness/errors"
)
type TagPartType string
const (
TagPartTypeKey TagPartType = "key"
TagPartTypeValue TagPartType = "value"
)
func SanitizeTag(text *string, typ TagPartType, requireNonEmpty bool) error {
if text == nil {
return nil
}
*text = strings.TrimSpace(*text)
if requireNonEmpty && len(*text) == 0 {
return errors.InvalidArgumentf("%s must be a non-empty string", typ)
}
const maxTagLength = 50
if utf8.RuneCountInString(*text) > maxTagLength {
return errors.InvalidArgumentf("%s can have at most %d characters", typ, maxTagLength)
}
for _, ch := range *text {
if unicode.IsControl(ch) {
return errors.InvalidArgumentf("%s cannot contain control characters", typ)
}
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/label.go | types/label.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"strings"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/types/enum"
)
type Label struct {
ID int64 `json:"id"`
SpaceID *int64 `json:"space_id,omitempty"`
RepoID *int64 `json:"repo_id,omitempty"`
Scope int64 `json:"scope"`
Key string `json:"key"`
Description string `json:"description"`
Type enum.LabelType `json:"type"`
Color enum.LabelColor `json:"color"`
ValueCount int64 `json:"value_count"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
CreatedBy int64 `json:"created_by"`
UpdatedBy int64 `json:"updated_by"`
PullreqCount int64 `json:"pullreq_count,omitempty"`
}
type LabelValue struct {
ID int64 `json:"id"`
LabelID int64 `json:"label_id"`
Value string `json:"value"`
Color enum.LabelColor `json:"color"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
CreatedBy int64 `json:"created_by"`
UpdatedBy int64 `json:"updated_by"`
}
type LabelWithValues struct {
Label `json:"label"`
Values []*LabelValue `json:"values,omitempty"`
}
// Used to assign label to pullreq.
type PullReqLabel struct {
PullReqID int64 `json:"pullreq_id"`
LabelID int64 `json:"label_id"`
ValueID *int64 `json:"value_id,omitempty"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
CreatedBy int64 `json:"created_by"`
UpdatedBy int64 `json:"updated_by"`
}
type LabelInfo struct {
SpaceID *int64 `json:"-"`
RepoID *int64 `json:"-"`
Scope int64 `json:"scope"`
ID int64 `json:"id"`
Type enum.LabelType `json:"type"`
Key string `json:"key"`
Color enum.LabelColor `json:"color"`
Assigned *bool `json:"assigned,omitempty"`
}
type LabelValueInfo struct {
LabelID *int64 `json:"-"`
ID *int64 `json:"id,omitempty"`
Value *string `json:"value,omitempty"`
Color *string `json:"color,omitempty"`
}
type LabelAssignment struct {
LabelInfo
AssignedValue *LabelValueInfo `json:"assigned_value,omitempty"`
Values []*LabelValueInfo `json:"values,omitempty"` // query param ?assignable=true
}
type LabelPullReqAssignmentInfo struct {
PullReqID int64 `json:"-"`
LabelID int64 `json:"id"`
LabelKey string `json:"key"`
LabelColor enum.LabelColor `json:"color,omitempty"`
LabelScope int64 `json:"scope"`
ValueCount int64 `json:"value_count"`
ValueID *int64 `json:"value_id,omitempty"`
Value *string `json:"value,omitempty"`
ValueColor *enum.LabelColor `json:"value_color,omitempty"`
}
type ScopeData struct {
// Scope = 0 is repo, scope >= 1 is a depth level of a space
Scope int64 `json:"scope"`
Space *SpaceCore `json:"space,omitempty"`
Repo *RepositoryCore `json:"repository,omitempty"`
}
// Used to fetch label and values from a repo and space hierarchy.
type ScopesLabels struct {
ScopeData []*ScopeData `json:"scope_data"`
LabelData []*LabelAssignment `json:"label_data"`
}
// LabelFilter stores label query parameters.
type AssignableLabelFilter struct {
ListQueryFilter
Assignable bool `json:"assignable,omitempty"`
}
type LabelFilter struct {
ListQueryFilter
Inherited bool `json:"inherited,omitempty"`
IncludePullreqCount bool `json:"pullreq_count,omitempty"`
}
type DefineLabelInput struct {
Key string `json:"key"`
Type enum.LabelType `json:"type"`
Description string `json:"description"`
Color enum.LabelColor `json:"color"`
}
func (in *DefineLabelInput) Sanitize() error {
if err := SanitizeTag(&in.Key, TagPartTypeKey, true); err != nil {
return err
}
sanitizeDescription(&in.Description)
if err := sanitizeLabelType(&in.Type); err != nil {
return err
}
if err := sanitizeLabelColor(&in.Color); err != nil {
return err
}
return nil
}
type UpdateLabelInput struct {
Key *string `json:"key,omitempty"`
Type *enum.LabelType `json:"type,omitempty"`
Description *string `json:"description,omitempty"`
Color *enum.LabelColor `json:"color,omitempty"`
}
func (in *UpdateLabelInput) Sanitize() error {
if err := SanitizeTag(in.Key, TagPartTypeKey, true); err != nil {
return err
}
sanitizeDescription(in.Description)
if err := sanitizeLabelType(in.Type); err != nil {
return err
}
if err := sanitizeLabelColor(in.Color); err != nil {
return err
}
return nil
}
type DefineValueInput struct {
Value string `json:"value"`
Color enum.LabelColor `json:"color"`
}
func (in *DefineValueInput) Sanitize() error {
if err := SanitizeTag(&in.Value, TagPartTypeValue, true); err != nil {
return err
}
if err := sanitizeLabelColor(&in.Color); err != nil {
return err
}
return nil
}
type UpdateValueInput struct {
Value *string `json:"value"`
Color *enum.LabelColor `json:"color"`
}
func (in *UpdateValueInput) Sanitize() error {
if in.Value != nil {
if err := SanitizeTag(in.Value, TagPartTypeValue, true); err != nil {
return err
}
}
if err := sanitizeLabelColor(in.Color); err != nil {
return err
}
return nil
}
type PullReqLabelAssignInput struct {
LabelID int64 `json:"label_id"`
ValueID *int64 `json:"value_id"`
Value string `json:"value"`
}
type PullReqUpdateInput struct {
LabelValueID *int64 `json:"label_value_id,omitempty"`
}
func (in PullReqLabelAssignInput) Validate() error {
if (in.ValueID != nil && *in.ValueID > 0) && in.Value != "" {
return errors.InvalidArgument("cannot accept both value id and value")
}
return nil
}
type SaveLabelInput struct {
ID int64 `json:"id"`
DefineLabelInput
}
type SaveLabelValueInput struct {
ID int64 `json:"id"`
DefineValueInput
}
type SaveInput struct {
Label SaveLabelInput `json:"label"`
Values []*SaveLabelValueInput `json:"values,omitempty"`
}
func (in *SaveInput) Sanitize() error {
if err := in.Label.Sanitize(); err != nil {
return err
}
for _, value := range in.Values {
if err := value.Sanitize(); err != nil {
return err
}
}
return nil
}
func sanitizeDescription(description *string) {
if description == nil {
return
}
*description = strings.TrimSpace(*description)
}
func sanitizeLabelType(typ *enum.LabelType) error {
if typ == nil {
return nil
}
*typ = enum.LabelType(trimLowerText(string(*typ)))
var ok bool
if *typ, ok = typ.Sanitize(); !ok {
return errors.InvalidArgument("invalid label type")
}
return nil
}
func sanitizeLabelColor(color *enum.LabelColor) error {
if color == nil {
return nil
}
*color = enum.LabelColor(trimLowerText(string(*color)))
var ok bool
if *color, ok = color.Sanitize(); !ok {
return errors.InvalidArgument("invalid label color")
}
return nil
}
func trimLowerText(text string) string {
return strings.ToLower(strings.TrimSpace(text))
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/gitspace_port.go | types/gitspace_port.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 types
import "github.com/harness/gitness/types/enum"
type GitspacePort struct {
Port int `json:"port"`
Protocol enum.CommunicationProtocol `json:"protocol"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/check/wire.go | types/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/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvidePrincipalUIDCheck,
ProvideSpaceIdentifierCheck,
ProvideRepoIdentifierCheck,
)
func ProvideSpaceIdentifierCheck() SpaceIdentifier {
return SpaceIdentifierDefault
}
func ProvidePrincipalUIDCheck() PrincipalUID {
return PrincipalUIDDefault
}
func ProvideRepoIdentifierCheck() RepoIdentifier {
return RepoIdentifierDefault
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/check/path.go | types/check/path.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package check
import (
"fmt"
"strings"
"github.com/harness/gitness/types"
)
const (
MaxSpacePathDepth = 9
MaxRepoPathDepth = 10
)
var (
ErrPathEmpty = &ValidationError{
"Path can't be empty.",
}
ErrPathInvalidDepth = &ValidationError{
fmt.Sprintf("A path can have at most %d segments (%d for spaces).",
MaxRepoPathDepth, MaxSpacePathDepth),
}
ErrEmptyPathSegment = &ValidationError{
"Empty segments are not allowed.",
}
ErrPathCantBeginOrEndWithSeparator = &ValidationError{
fmt.Sprintf("Path can't start or end with the separator ('%s').", types.PathSeparatorAsString),
}
)
// Path checks the provided path and returns an error in it isn't valid.
func Path(path string, isSpace bool, identifierCheck SpaceIdentifier) error {
if path == "" {
return ErrPathEmpty
}
// ensure path doesn't begin or end with /
if path[:1] == types.PathSeparatorAsString || path[len(path)-1:] == types.PathSeparatorAsString {
return ErrPathCantBeginOrEndWithSeparator
}
// ensure path is not too deep
if err := PathDepth(path, isSpace); err != nil {
return err
}
// ensure all segments of the path are valid identifiers
segments := strings.Split(path, types.PathSeparatorAsString)
for i, s := range segments {
if s == "" {
return ErrEmptyPathSegment
} else if err := identifierCheck(s, i == 0); err != nil {
return fmt.Errorf("invalid segment '%s': %w", s, err)
}
}
return nil
}
// PathDepth Checks the depth of the provided path.
func PathDepth(path string, isSpace bool) error {
if IsPathTooDeep(path, isSpace) {
return ErrPathInvalidDepth
}
return nil
}
// IsPathTooDeep Checks if the provided path is too long.
// NOTE: A repository path can be one deeper than a space path (as otherwise the space would be useless).
func IsPathTooDeep(path string, isSpace bool) bool {
l := strings.Count(path, types.PathSeparatorAsString) + 1
return (!isSpace && l > MaxRepoPathDepth) || (isSpace && l > MaxSpacePathDepth)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/check/error.go | types/check/error.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package check
import (
"errors"
"fmt"
)
var (
ErrAny = &ValidationError{}
)
// ValidationError is error returned for any validation errors.
// WARNING: This error will be printed to the user as is!
type ValidationError struct {
msg string
}
func NewValidationError(msg string) *ValidationError {
return &ValidationError{
msg: msg,
}
}
func NewValidationErrorf(format string, args ...any) *ValidationError {
return &ValidationError{
msg: fmt.Sprintf(format, args...),
}
}
func (e *ValidationError) Error() string {
return e.msg
}
func (e *ValidationError) Is(target error) bool {
// If the caller is checking for any ValidationError, return true
if errors.Is(target, ErrAny) {
return true
}
// ensure it's the correct type
err := &ValidationError{}
if !errors.As(target, &err) {
return false
}
// only the same if the message is the same
return e.msg == err.msg
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/check/token.go | types/check/token.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package check
import (
"time"
)
const (
minTokenLifeTime = 24 * time.Hour // 1 day
maxTokenLifeTime = 365 * 24 * time.Hour // 1 year
)
var (
ErrTokenLifeTimeOutOfBounds = &ValidationError{
"The life time of a token has to be between 1 day and 365 days.",
}
ErrTokenLifeTimeRequired = &ValidationError{
"The life time of a token is required.",
}
)
// TokenLifetime returns true if the lifetime is valid for a token.
func TokenLifetime(lifetime *time.Duration, optional bool) error {
if lifetime == nil && !optional {
return ErrTokenLifeTimeRequired
}
if lifetime == nil {
return nil
}
if *lifetime < minTokenLifeTime || *lifetime > maxTokenLifeTime {
return ErrTokenLifeTimeOutOfBounds
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/check/password.go | types/check/password.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 (
"fmt"
)
const (
minPasswordLength = 1
maxPasswordLength = 128
)
var (
// ErrPasswordLength is returned when the password
// is outside of the allowed length.
ErrPasswordLength = &ValidationError{
fmt.Sprintf("Password has to be within %d and %d characters", minPasswordLength, maxPasswordLength),
}
)
// Password returns true if the Password is valid.
// TODO: add proper password checks.
func Password(pw string) error {
// validate length
l := len(pw)
if l < minPasswordLength || l > maxPasswordLength {
return ErrPasswordLength
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/check/service_account.go | types/check/service_account.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/types/enum"
)
var (
ErrServiceAccountParentTypeIsInvalid = &ValidationError{
"Provided parent type is invalid.",
}
ErrServiceAccountParentIDInvalid = &ValidationError{
"ParentID required - Global service accounts are not supported.",
}
)
// ServiceAccountParent verifies the remaining fields of a service account
// that aren't inherited from principal.
func ServiceAccountParent(parentType enum.ParentResourceType, parentID int64) error {
if parentType != enum.ParentResourceTypeRepo && parentType != enum.ParentResourceTypeSpace {
return ErrServiceAccountParentTypeIsInvalid
}
// validate service account belongs to sth
if parentID <= 0 {
return ErrServiceAccountParentIDInvalid
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/check/common.go | types/check/common.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package check
import (
"fmt"
"regexp"
"slices"
"strings"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types"
)
const (
minDisplayNameLength = 1
maxDisplayNameLength = 256
minIdentifierLength = 1
MaxIdentifierLength = 100
identifierRegex = "^[a-zA-Z0-9-_.]*$"
illegalRepoSpaceIdentifierSuffix = ".git"
minEmailLength = 1
maxEmailLength = 250
maxDescriptionLength = 1024
)
var (
// illegalRootSpaceIdentifiers is the list of space identifier we are blocking for root spaces
// as they might cause issues with routing.
illegalRootSpaceIdentifiers = []string{"api", "git"}
)
var (
ErrDisplayNameLength = &ValidationError{
fmt.Sprintf("DisplayName has to be between %d and %d in length.", minDisplayNameLength, maxDisplayNameLength),
}
ErrDescriptionTooLong = &ValidationError{
fmt.Sprintf("Description can be at most %d in length.", maxDescriptionLength),
}
ErrIdentifierLength = &ValidationError{
fmt.Sprintf(
"Identifier has to be between %d and %d in length.",
minIdentifierLength,
MaxIdentifierLength,
),
}
ErrIdentifierRegex = &ValidationError{
"Identifier can only contain the following characters [a-zA-Z0-9-_.].",
}
ErrEmailLen = &ValidationError{
fmt.Sprintf("Email address has to be within %d and %d characters", minEmailLength, maxEmailLength),
}
ErrInvalidCharacters = &ValidationError{"Input contains invalid characters."}
ErrIllegalRootSpaceIdentifier = &ValidationError{
fmt.Sprintf("The following identifiers are not allowed for a root space: %v", illegalRootSpaceIdentifiers),
}
ErrIllegalRootSpaceIdentifierNumber = &ValidationError{"The identifier of a root space can't be numeric."}
ErrIllegalRepoSpaceIdentifierSuffix = &ValidationError{
fmt.Sprintf("Space and repository identifiers cannot end with %q.", illegalRepoSpaceIdentifierSuffix),
}
ErrIllegalPrincipalUID = &ValidationError{
fmt.Sprintf("Principal UID is not allowed to be %q.", types.AnonymousPrincipalUID),
}
)
// DisplayName checks the provided display name and returns an error if it isn't valid.
func DisplayName(displayName string) error {
l := len(displayName)
if l < minDisplayNameLength || l > maxDisplayNameLength {
return ErrDisplayNameLength
}
return ForControlCharacters(displayName)
}
// Description checks the provided description and returns an error if it isn't valid.
func Description(description string) error {
l := len(description)
if l > maxDescriptionLength {
return ErrDescriptionTooLong
}
return ForControlCharacters(description)
}
// ForControlCharacters ensures that there are no control characters in the provided string.
func ForControlCharacters(s string) error {
for _, r := range s {
if r < 32 || r == 127 {
return ErrInvalidCharacters
}
}
return nil
}
// Identifier checks the provided identifier and returns an error if it isn't valid.
func Identifier(identifier string) error {
l := len(identifier)
if l < minIdentifierLength || l > MaxIdentifierLength {
return ErrIdentifierLength
}
if ok, _ := regexp.Match(identifierRegex, []byte(identifier)); !ok {
return ErrIdentifierRegex
}
return nil
}
type RepoIdentifier func(identifier string, session *auth.Session) error
// RepoIdentifierDefault performs the default Identifier check and also blocks illegal repo identifiers.
func RepoIdentifierDefault(identifier string, _ *auth.Session) error {
if err := Identifier(identifier); err != nil {
return err
}
identifierLower := strings.ToLower(identifier)
if strings.HasSuffix(identifierLower, illegalRepoSpaceIdentifierSuffix) {
return ErrIllegalRepoSpaceIdentifierSuffix
}
return nil
}
// PrincipalUID is an abstraction of a validation method that verifies principal UIDs.
// NOTE: Enables support for different principal UID formats.
type PrincipalUID func(uid string) error
// PrincipalUIDDefault performs the default Principal UID check.
func PrincipalUIDDefault(uid string) error {
if err := Identifier(uid); err != nil {
return err
}
if strings.EqualFold(uid, types.AnonymousPrincipalUID) {
return ErrIllegalPrincipalUID
}
return nil
}
// SpaceIdentifier is an abstraction of a validation method that returns true
// iff the Identifier is valid to be used in a resource path for repo/space.
// NOTE: Enables support for different path formats.
type SpaceIdentifier func(identifier string, isRoot bool) error
// SpaceIdentifierDefault performs the default Identifier check and also blocks illegal root space Identifiers.
func SpaceIdentifierDefault(identifier string, isRoot bool) error {
if err := Identifier(identifier); err != nil {
return err
}
identifierLower := strings.ToLower(identifier)
if strings.HasSuffix(identifierLower, illegalRepoSpaceIdentifierSuffix) {
return ErrIllegalRepoSpaceIdentifierSuffix
}
if isRoot {
// root space identifier can't be numeric as it would cause conflicts of space path and space id.
if strings.TrimLeftFunc(identifier, func(r rune) bool { return r >= '0' && r <= '9' }) == "" {
return ErrIllegalRootSpaceIdentifierNumber
}
if slices.Contains(illegalRootSpaceIdentifiers, identifierLower) {
return ErrIllegalRootSpaceIdentifier
}
}
return nil
}
// Email checks the provided email and returns an error if it isn't valid.
func Email(email string) error {
l := len(email)
if l < minEmailLength || l > maxEmailLength {
return ErrEmailLen
}
// TODO: add better email validation.
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/feature_option_value_type.go | types/enum/feature_option_value_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type FeatureOptionValueType string
func (FeatureOptionValueType) Enum() []any { return toInterfaceSlice(featureOptionValueTypes) }
const (
FeatureOptionValueTypeString = "string"
FeatureOptionValueTypeBoolean = "boolean"
)
var featureOptionValueTypes = sortEnum([]ExecutionSort{
FeatureOptionValueTypeString,
FeatureOptionValueTypeBoolean,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/git.go | types/enum/git.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"fmt"
"strings"
)
// BranchSortOption specifies the available sort options for branches.
type BranchSortOption int
const (
BranchSortOptionDefault BranchSortOption = iota
BranchSortOptionName
BranchSortOptionDate
)
// ParseBranchSortOption parses the branch sort option string
// and returns the equivalent enumeration.
func ParseBranchSortOption(s string) BranchSortOption {
switch strings.ToLower(s) {
case name:
return BranchSortOptionName
case date:
return BranchSortOptionDate
default:
return BranchSortOptionDefault
}
}
// String returns a string representation of the branch sort option.
func (o BranchSortOption) String() string {
switch o {
case BranchSortOptionName:
return name
case BranchSortOptionDate:
return date
case BranchSortOptionDefault:
return defaultString
default:
return undefined
}
}
// TagSortOption specifies the available sort options for tags.
type TagSortOption int
const (
TagSortOptionDefault TagSortOption = iota
TagSortOptionName
TagSortOptionDate
)
// ParseTagSortOption parses the tag sort option string
// and returns the equivalent enumeration.
func ParseTagSortOption(s string) TagSortOption {
switch strings.ToLower(s) {
case name:
return TagSortOptionName
case date:
return TagSortOptionDate
default:
return TagSortOptionDefault
}
}
// String returns a string representation of the tag sort option.
func (o TagSortOption) String() string {
switch o {
case TagSortOptionName:
return name
case TagSortOptionDate:
return date
case TagSortOptionDefault:
return defaultString
default:
return undefined
}
}
// GitServiceType represents the different types of service values send by git's smart http protocol.
// See https://git-scm.com/docs/http-protocol#_smart_clients for more details.
type GitServiceType string
const (
// GitServiceTypeReceivePack is sent by git push operations (server "receives" data from client).
GitServiceTypeReceivePack GitServiceType = "receive-pack"
// GitServiceTypeUploadPack is sent by git pull operations (server "uploads" data to client).
GitServiceTypeUploadPack GitServiceType = "upload-pack"
)
// ParseGitServiceType parses the git service type string and returns the equivalent enumeration.
// If the value is unknown and doesn't represent a git service type, an error is returned.
func ParseGitServiceType(s string) (GitServiceType, error) {
switch strings.ToLower(s) {
case string(GitServiceTypeReceivePack):
return GitServiceTypeReceivePack, nil
case string(GitServiceTypeUploadPack):
return GitServiceTypeUploadPack, nil
default:
return "", fmt.Errorf("unknown git service type provided: %q", s)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/membership_role.go | types/enum/membership_role.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "golang.org/x/exp/slices"
// MembershipRole represents the different level of space memberships (permission set).
type MembershipRole string
func (MembershipRole) Enum() []any { return toInterfaceSlice(MembershipRoles) }
func (m MembershipRole) Sanitize() (MembershipRole, bool) { return Sanitize(m, GetAllMembershipRoles) }
func GetAllMembershipRoles() ([]MembershipRole, MembershipRole) { return MembershipRoles, "" }
var MembershipRoles = sortEnum([]MembershipRole{
MembershipRoleReader,
MembershipRoleExecutor,
MembershipRoleContributor,
MembershipRoleSpaceOwner,
})
var membershipRoleReaderPermissions = slices.Clip(slices.Insert([]Permission{}, 0,
PermissionRepoView,
PermissionSpaceView,
PermissionServiceAccountView,
PermissionPipelineView,
PermissionSecretView,
PermissionConnectorView,
PermissionTemplateView,
PermissionGitspaceView,
PermissionInfraProviderView,
PermissionArtifactsDownload,
PermissionRegistryView,
))
var membershipRoleExecutorPermissions = slices.Clip(slices.Insert(membershipRoleReaderPermissions, 0,
PermissionRepoReportCommitCheck,
PermissionPipelineExecute,
PermissionSecretAccess,
PermissionConnectorAccess,
PermissionTemplateAccess,
PermissionGitspaceUse,
PermissionArtifactsUpload,
))
var membershipRoleContributorPermissions = slices.Clip(slices.Insert(membershipRoleReaderPermissions, 0,
PermissionRepoPush,
PermissionRepoReview,
PermissionArtifactsUpload,
PermissionArtifactsDelete,
PermissionGitspaceCreate,
PermissionGitspaceEdit,
PermissionGitspaceDelete,
PermissionGitspaceUse,
))
var membershipRoleSpaceOwnerPermissions = slices.Clip(slices.Insert(membershipRoleReaderPermissions, 0,
PermissionRepoCreate,
PermissionRepoEdit,
PermissionRepoDelete,
PermissionRepoPush,
PermissionRepoReportCommitCheck,
PermissionRepoReview,
PermissionSpaceEdit,
PermissionSpaceDelete,
PermissionServiceAccountEdit,
PermissionServiceAccountDelete,
PermissionPipelineEdit,
PermissionPipelineExecute,
PermissionPipelineDelete,
PermissionSecretAccess,
PermissionSecretDelete,
PermissionSecretEdit,
PermissionConnectorAccess,
PermissionConnectorDelete,
PermissionConnectorEdit,
PermissionTemplateAccess,
PermissionTemplateDelete,
PermissionTemplateEdit,
PermissionGitspaceCreate,
PermissionGitspaceEdit,
PermissionGitspaceDelete,
PermissionGitspaceUse,
PermissionInfraProviderEdit,
PermissionInfraProviderDelete,
PermissionArtifactsUpload,
PermissionArtifactsDelete,
PermissionArtifactsQuarantine,
PermissionRegistryEdit,
PermissionRegistryDelete,
))
func init() {
slices.Sort(membershipRoleReaderPermissions)
slices.Sort(membershipRoleExecutorPermissions)
slices.Sort(membershipRoleContributorPermissions)
slices.Sort(membershipRoleSpaceOwnerPermissions)
}
// Permissions returns the list of permissions for the role.
func (m MembershipRole) Permissions() []Permission {
switch m {
case MembershipRoleReader:
return membershipRoleReaderPermissions
case MembershipRoleExecutor:
return membershipRoleExecutorPermissions
case MembershipRoleContributor:
return membershipRoleContributorPermissions
case MembershipRoleSpaceOwner:
return membershipRoleSpaceOwnerPermissions
default:
return nil
}
}
const (
MembershipRoleReader MembershipRole = "reader"
MembershipRoleExecutor MembershipRole = "executor"
MembershipRoleContributor MembershipRole = "contributor"
MembershipRoleSpaceOwner MembershipRole = "space_owner"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/order.go | types/enum/order.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"strings"
)
// Order defines the sort order.
type Order int
// Order enumeration.
const (
OrderDefault Order = iota
OrderAsc
OrderDesc
)
// String returns the Order as a string.
func (e Order) String() string {
switch e {
case OrderDesc:
return desc
case OrderAsc:
return asc
case OrderDefault:
return desc
default:
return undefined
}
}
// ParseOrder parses the order string and returns
// an order enumeration.
func ParseOrder(s string) Order {
switch strings.ToLower(s) {
case asc, ascending:
return OrderAsc
case desc, descending:
return OrderDesc
default:
return OrderDefault
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/job.go | types/enum/job.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// JobState represents state of a background job.
type JobState string
// JobState enumeration.
const (
JobStateScheduled JobState = "scheduled"
JobStateRunning JobState = "running"
JobStateFinished JobState = "finished"
JobStateFailed JobState = "failed"
JobStateCanceled JobState = "canceled"
)
var jobStates = sortEnum([]JobState{
JobStateScheduled,
JobStateRunning,
JobStateFinished,
JobStateFailed,
JobStateCanceled,
})
func (JobState) Enum() []any { return toInterfaceSlice(jobStates) }
func (s JobState) Sanitize() (JobState, bool) {
return Sanitize(s, GetAllJobStates)
}
func GetAllJobStates() ([]JobState, JobState) {
return jobStates, ""
}
// JobPriority represents priority of a background job.
type JobPriority int
// JobPriority enumeration.
const (
JobPriorityNormal JobPriority = 0
JobPriorityElevated JobPriority = 1
)
func (s JobState) IsCompleted() bool {
return s == JobStateFinished || s == JobStateFailed || s == JobStateCanceled
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/common_test.go | types/enum/common_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"testing"
)
func TestSanitizeString(t *testing.T) {
// Test with string type
allValues := func() ([]string, string) {
return []string{"apple", "banana", "cherry"}, "apple"
}
tests := []struct {
name string
element string
expectedResult string
expectedFound bool
}{
{
name: "valid element",
element: "banana",
expectedResult: "banana",
expectedFound: true,
},
{
name: "empty element returns default",
element: "",
expectedResult: "apple",
expectedFound: true,
},
{
name: "invalid element returns default",
element: "grape",
expectedResult: "apple",
expectedFound: false,
},
{
name: "first element",
element: "apple",
expectedResult: "apple",
expectedFound: true,
},
{
name: "last element",
element: "cherry",
expectedResult: "cherry",
expectedFound: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, found := Sanitize(tt.element, allValues)
if result != tt.expectedResult {
t.Errorf("Expected result %q, got %q", tt.expectedResult, result)
}
if found != tt.expectedFound {
t.Errorf("Expected found %v, got %v", tt.expectedFound, found)
}
})
}
}
func TestSanitizeInt(t *testing.T) {
// Test with int type
allValues := func() ([]int, int) {
return []int{1, 3, 5, 7, 9}, 1
}
tests := []struct {
name string
element int
expectedResult int
expectedFound bool
}{
{
name: "valid element",
element: 5,
expectedResult: 5,
expectedFound: true,
},
{
name: "zero element returns default",
element: 0,
expectedResult: 1,
expectedFound: true,
},
{
name: "invalid element returns default",
element: 4,
expectedResult: 1,
expectedFound: false,
},
{
name: "first element",
element: 1,
expectedResult: 1,
expectedFound: true,
},
{
name: "last element",
element: 9,
expectedResult: 9,
expectedFound: true,
},
{
name: "negative element returns default",
element: -1,
expectedResult: 1,
expectedFound: false,
},
{
name: "large element returns default",
element: 100,
expectedResult: 1,
expectedFound: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, found := Sanitize(tt.element, allValues)
if result != tt.expectedResult {
t.Errorf("Expected result %d, got %d", tt.expectedResult, result)
}
if found != tt.expectedFound {
t.Errorf("Expected found %v, got %v", tt.expectedFound, found)
}
})
}
}
func TestSanitizeFloat64(t *testing.T) {
// Test with float64 type
allValues := func() ([]float64, float64) {
return []float64{1.1, 2.2, 3.3}, 1.1
}
tests := []struct {
name string
element float64
expectedResult float64
expectedFound bool
}{
{
name: "valid element",
element: 2.2,
expectedResult: 2.2,
expectedFound: true,
},
{
name: "zero element returns default",
element: 0.0,
expectedResult: 1.1,
expectedFound: true,
},
{
name: "invalid element returns default",
element: 4.4,
expectedResult: 1.1,
expectedFound: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, found := Sanitize(tt.element, allValues)
if result != tt.expectedResult {
t.Errorf("Expected result %f, got %f", tt.expectedResult, result)
}
if found != tt.expectedFound {
t.Errorf("Expected found %v, got %v", tt.expectedFound, found)
}
})
}
}
func TestSanitizeEmptySlice(t *testing.T) {
// Test with empty slice
allValues := func() ([]string, string) {
return []string{}, "default"
}
result, found := Sanitize("any", allValues)
if result != "default" {
t.Errorf("Expected result %q, got %q", "default", result)
}
if found {
t.Errorf("Expected found to be false, got %v", found)
}
}
func TestSanitizeEmptyDefault(t *testing.T) {
// Test with empty default value
allValues := func() ([]string, string) {
return []string{"apple", "banana"}, ""
}
tests := []struct {
name string
element string
expectedResult string
expectedFound bool
}{
{
name: "valid element",
element: "apple",
expectedResult: "apple",
expectedFound: true,
},
{
name: "empty element with empty default",
element: "",
expectedResult: "",
expectedFound: false,
},
{
name: "invalid element returns empty default",
element: "grape",
expectedResult: "",
expectedFound: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, found := Sanitize(tt.element, allValues)
if result != tt.expectedResult {
t.Errorf("Expected result %q, got %q", tt.expectedResult, result)
}
if found != tt.expectedFound {
t.Errorf("Expected found %v, got %v", tt.expectedFound, found)
}
})
}
}
func TestSanitizeWithOrder(t *testing.T) {
// Test with Order enum type
allValues := func() ([]Order, Order) {
return []Order{OrderDefault, OrderAsc, OrderDesc}, OrderDefault
}
tests := []struct {
name string
element Order
expectedResult Order
expectedFound bool
}{
{
name: "valid order",
element: OrderAsc,
expectedResult: OrderAsc,
expectedFound: true,
},
{
name: "zero order returns default",
element: Order(0),
expectedResult: OrderDefault,
expectedFound: true,
},
{
name: "invalid order returns default",
element: Order(999),
expectedResult: OrderDefault,
expectedFound: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, found := Sanitize(tt.element, allValues)
if result != tt.expectedResult {
t.Errorf("Expected result %v, got %v", tt.expectedResult, result)
}
if found != tt.expectedFound {
t.Errorf("Expected found %v, got %v", tt.expectedFound, found)
}
})
}
}
func TestToInterfaceSlice(t *testing.T) {
// Test string slice
stringSlice := []string{"a", "b", "c"}
result := toInterfaceSlice(stringSlice)
if len(result) != len(stringSlice) {
t.Errorf("Expected length %d, got %d", len(stringSlice), len(result))
}
for i, v := range result {
if v != stringSlice[i] {
t.Errorf("Expected element %d to be %v, got %v", i, stringSlice[i], v)
}
}
// Test int slice
intSlice := []int{1, 2, 3}
result = toInterfaceSlice(intSlice)
if len(result) != len(intSlice) {
t.Errorf("Expected length %d, got %d", len(intSlice), len(result))
}
for i, v := range result {
if v != intSlice[i] {
t.Errorf("Expected element %d to be %v, got %v", i, intSlice[i], v)
}
}
// Test empty slice
emptySlice := []string{}
result = toInterfaceSlice(emptySlice)
if len(result) != 0 {
t.Errorf("Expected empty slice, got length %d", len(result))
}
}
func TestSortEnum(t *testing.T) {
// Test string sorting
stringSlice := []string{"zebra", "apple", "banana"}
sorted := sortEnum(stringSlice)
expected := []string{"apple", "banana", "zebra"}
if len(sorted) != len(expected) {
t.Errorf("Expected length %d, got %d", len(expected), len(sorted))
}
for i, v := range sorted {
if v != expected[i] {
t.Errorf("Expected element %d to be %q, got %q", i, expected[i], v)
}
}
// Test int sorting
intSlice := []int{3, 1, 4, 1, 5}
sortedInt := sortEnum(intSlice)
expectedInt := []int{1, 1, 3, 4, 5}
if len(sortedInt) != len(expectedInt) {
t.Errorf("Expected length %d, got %d", len(expectedInt), len(sortedInt))
}
for i, v := range sortedInt {
if v != expectedInt[i] {
t.Errorf("Expected element %d to be %d, got %d", i, expectedInt[i], v)
}
}
// Test empty slice
emptySlice := []string{}
sortedEmpty := sortEnum(emptySlice)
if len(sortedEmpty) != 0 {
t.Errorf("Expected empty slice, got length %d", len(sortedEmpty))
}
// Test single element
singleSlice := []string{"single"}
sortedSingle := sortEnum(singleSlice)
if len(sortedSingle) != 1 || sortedSingle[0] != "single" {
t.Errorf("Expected single element slice with 'single', got %v", sortedSingle)
}
}
// Benchmark tests.
func BenchmarkSanitizeString(b *testing.B) {
allValues := func() ([]string, string) {
return []string{"apple", "banana", "cherry"}, "apple"
}
for b.Loop() {
Sanitize("banana", allValues)
}
}
func BenchmarkSanitizeInt(b *testing.B) {
allValues := func() ([]int, int) {
return []int{1, 3, 5, 7, 9}, 1
}
for b.Loop() {
Sanitize(5, allValues)
}
}
func BenchmarkToInterfaceSlice(b *testing.B) {
stringSlice := []string{"a", "b", "c", "d", "e"}
for b.Loop() {
toInterfaceSlice(stringSlice)
}
}
func BenchmarkSortEnum(b *testing.B) {
stringSlice := []string{"zebra", "apple", "banana", "cherry", "date"}
for b.Loop() {
sortEnum(stringSlice)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/order_test.go | types/enum/order_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import "testing"
func TestParseOrder(t *testing.T) {
tests := []struct {
text string
want Order
}{
{"asc", OrderAsc},
{"Asc", OrderAsc},
{"ASC", OrderAsc},
{"ascending", OrderAsc},
{"Ascending", OrderAsc},
{"ASCENDING", OrderAsc},
{"desc", OrderDesc},
{"Desc", OrderDesc},
{"DESC", OrderDesc},
{"descending", OrderDesc},
{"Descending", OrderDesc},
{"DESCENDING", OrderDesc},
{"", OrderDefault},
{"invalid", OrderDefault},
{"random", OrderDefault},
{"123", OrderDefault},
{"asc ", OrderDefault}, // trailing space
{" asc", OrderDefault}, // leading space
{"asc\n", OrderDefault}, // newline
{"asc\t", OrderDefault}, // tab
{"ascend", OrderDefault}, // partial match
{"descend", OrderDefault}, // partial match
{"ascc", OrderDefault}, // typo
{"descc", OrderDefault}, // typo
{"null", OrderDefault},
{"undefined", OrderDefault},
}
for _, test := range tests {
t.Run(test.text, func(t *testing.T) {
got, want := ParseOrder(test.text), test.want
if got != want {
t.Errorf("Want order %q parsed as %q, got %q", test.text, want, got)
}
})
}
}
func TestOrderString(t *testing.T) {
tests := []struct {
order Order
want string
}{
{OrderDefault, "desc"}, // OrderDefault returns desc
{OrderAsc, "asc"},
{OrderDesc, "desc"},
{Order(999), "undefined"}, // invalid order value
{Order(-1), "undefined"}, // negative order value
{Order(100), "undefined"}, // large order value
}
for _, test := range tests {
t.Run(test.want, func(t *testing.T) {
got := test.order.String()
if got != test.want {
t.Errorf("Want order %v as string %q, got %q", test.order, test.want, got)
}
})
}
}
func TestOrderConstants(t *testing.T) {
// Test that the constants have expected values
if OrderDefault != 0 {
t.Errorf("Expected OrderDefault to be 0, got %d", OrderDefault)
}
if OrderAsc != 1 {
t.Errorf("Expected OrderAsc to be 1, got %d", OrderAsc)
}
if OrderDesc != 2 {
t.Errorf("Expected OrderDesc to be 2, got %d", OrderDesc)
}
}
func TestOrderStringRoundTrip(t *testing.T) {
// Test that parsing the string representation gives back the original order
orders := []Order{OrderDefault, OrderAsc, OrderDesc}
for _, order := range orders {
t.Run(order.String(), func(t *testing.T) {
str := order.String()
parsed := ParseOrder(str)
// Note: OrderDefault.String() returns "desc", so parsing it gives OrderDesc
// This is expected behavior based on the implementation
if order == OrderDefault {
if parsed != OrderDesc {
t.Errorf("Expected parsing OrderDefault string to give OrderDesc, got %v", parsed)
}
} else {
if parsed != order {
t.Errorf("Expected parsing %v string to give %v, got %v", order, order, parsed)
}
}
})
}
}
func TestOrderComparison(t *testing.T) {
// Test that orders can be compared
if OrderDefault >= OrderAsc {
t.Error("Expected OrderDefault < OrderAsc")
}
if OrderAsc >= OrderDesc {
t.Error("Expected OrderAsc < OrderDesc")
}
if OrderDefault >= OrderDesc {
t.Error("Expected OrderDefault < OrderDesc")
}
}
func TestOrderType(t *testing.T) {
// Test that Order is the correct type
var o Order
if o != OrderDefault {
t.Errorf("Expected zero value of Order to be OrderDefault, got %v", o)
}
// Test type conversion
o = Order(1)
if o != OrderAsc {
t.Errorf("Expected Order(1) to be OrderAsc, got %v", o)
}
}
// Benchmark tests.
func BenchmarkParseOrder(b *testing.B) {
for b.Loop() {
ParseOrder("asc")
}
}
func BenchmarkParseOrderDesc(b *testing.B) {
for b.Loop() {
ParseOrder("desc")
}
}
func BenchmarkParseOrderInvalid(b *testing.B) {
for b.Loop() {
ParseOrder("invalid")
}
}
func BenchmarkOrderString(b *testing.B) {
for b.Loop() {
_ = OrderAsc.String()
}
}
func BenchmarkOrderStringDesc(b *testing.B) {
for b.Loop() {
_ = OrderDesc.String()
}
}
func BenchmarkOrderStringDefault(b *testing.B) {
for b.Loop() {
_ = OrderDefault.String()
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/connector_status.go | types/enum/connector_status.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
// ConnectorStatus represents the status of the connector after testing connection.
type ConnectorStatus string
const (
ConnectorStatusSuccess ConnectorStatus = "success"
ConnectorStatusFailed ConnectorStatus = "failed"
)
func (s ConnectorStatus) String() string {
switch s {
case ConnectorStatusSuccess:
return "success"
case ConnectorStatusFailed:
return "failed"
default:
return undefined
}
}
func GetAllConnectorStatus() ([]ConnectorStatus, ConnectorStatus) {
return connectorStatus, "" // No default value
}
var connectorStatus = sortEnum([]ConnectorStatus{
ConnectorStatusSuccess,
ConnectorStatusFailed,
})
func (ConnectorStatus) Enum() []any { return toInterfaceSlice(connectorStatus) }
func (s ConnectorStatus) Sanitize() (ConnectorStatus, bool) {
return Sanitize(s, GetAllConnectorStatus)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/types/enum/feature_source_type.go | types/enum/feature_source_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type FeatureSourceType string
func (FeatureSourceType) Enum() []any { return toInterfaceSlice(featureSourceTypes) }
const (
FeatureSourceTypeOCI = "oci"
FeatureSourceTypeTarball = "tarball"
FeatureSourceTypeLocal = "local"
)
var featureSourceTypes = sortEnum([]ExecutionSort{
FeatureSourceTypeOCI,
FeatureSourceTypeTarball,
FeatureSourceTypeLocal,
})
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.