setting

package
v1.22.0-rc0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 28, 2024 License: MIT Imports: 39 Imported by: 2,373

Documentation

Index

Constants

View Source
const (
	UserFeatureDeletion      = "deletion"
	UserFeatureManageSSHKeys = "manage_ssh_keys"
	UserFeatureManageGPGKeys = "manage_gpg_keys"
)
View Source
const (
	EnvConfigKeyPrefixGitea = "GITEA__"
	EnvConfigKeySuffixFile  = "__FILE"
)
View Source
const (
	RenderContentModeSanitized   = "sanitized"
	RenderContentModeNoSanitizer = "no-sanitizer"
	RenderContentModeIframe      = "iframe"
)
View Source
const (
	RepoCreatingLastUserVisibility = "last"
	RepoCreatingPrivate            = "private"
	RepoCreatingPublic             = "public"
)

enumerates all the policy repository creating

View Source
const (
	ImageCaptcha = "image"
	ReCaptcha    = "recaptcha"
	HCaptcha     = "hcaptcha"
	MCaptcha     = "mcaptcha"
	CfTurnstile  = "cfturnstile"
)

enumerates all the types of captchas

View Source
const HasBuiltinBindata = false
View Source
const ItemsPerPage = 40

ItemsPerPage maximum items per page in forks, watchers and stars of a repo

View Source
const MemcacheMaxTTL = 30 * 24 * time.Hour

MemcacheMaxTTL represents the maximum memcache TTL

Variables

View Source
var (
	// SupportedDatabaseTypes includes all XORM supported databases type, sqlite3 maybe added by `database_sqlite3.go`
	SupportedDatabaseTypes = []string{"mysql", "postgres", "mssql"}
	// DatabaseTypeNames contains the friendly names for all database types
	DatabaseTypeNames = map[string]string{"mysql": "MySQL", "postgres": "PostgreSQL", "mssql": "MSSQL", "sqlite3": "SQLite3"}

	// EnableSQLite3 use SQLite3, set by build flag
	EnableSQLite3 bool

	// Database holds the database settings
	Database = struct {
		Type               DatabaseType
		Host               string
		Name               string
		User               string
		Passwd             string
		Schema             string
		SSLMode            string
		Path               string
		LogSQL             bool
		MysqlCharset       string
		CharsetCollation   string
		Timeout            int // seconds
		SQLiteJournalMode  string
		DBConnectRetries   int
		DBConnectBackoff   time.Duration
		MaxIdleConns       int
		MaxOpenConns       int
		ConnMaxLifetime    time.Duration
		IterateBufferSize  int
		AutoMigration      bool
		SlowQueryThreshold time.Duration
	}{
		Timeout:           500,
		IterateBufferSize: 50,
	}
)
View Source
var (
	// I18n settings
	Langs []string
	Names []string
)
View Source
var (
	ExternalMarkupRenderers    []*MarkupRenderer
	ExternalSanitizerRules     []MarkupSanitizerRule
	MermaidMaxSourceCharacters int
)

ExternalMarkupRenderers represents the external markup renderers

View Source
var (
	// AppPath represents the path to the gitea binary
	AppPath string

	// AppWorkPath is the "working directory" of Gitea. It maps to the: WORK_PATH in app.ini, "--work-path" flag, environment variable GITEA_WORK_DIR.
	// If that is not set it is the default set here by the linker or failing that the directory of AppPath.
	// It is used as the base path for several other paths.
	AppWorkPath string
	CustomPath  string // Custom directory path. Env: GITEA_CUSTOM
	CustomConf  string

	AppWorkPathMismatch bool
)
View Source
var (
	Avatar = struct {
		Storage *Storage

		MaxWidth           int
		MaxHeight          int
		MaxFileSize        int64
		MaxOriginSize      int64
		RenderedSizeFactor int
	}{
		MaxWidth:           4096,
		MaxHeight:          4096,
		MaxFileSize:        1048576,
		MaxOriginSize:      262144,
		RenderedSizeFactor: 2,
	}

	GravatarSource        string
	DisableGravatar       bool // Depreciated: migrated to database
	EnableFederatedAvatar bool // Depreciated: migrated to database

	RepoAvatar = struct {
		Storage *Storage

		Fallback      string
		FallbackImage string
	}{}
)
View Source
var (
	Repository = struct {
		DetectedCharsetsOrder                   []string
		DetectedCharsetScore                    map[string]int `ini:"-"`
		AnsiCharset                             string
		ForcePrivate                            bool
		DefaultPrivate                          string
		DefaultPushCreatePrivate                bool
		MaxCreationLimit                        int
		PreferredLicenses                       []string
		DisableHTTPGit                          bool
		AccessControlAllowOrigin                string
		UseCompatSSHURI                         bool
		GoGetCloneURLProtocol                   string
		DefaultCloseIssuesViaCommitsInAnyBranch bool
		EnablePushCreateUser                    bool
		EnablePushCreateOrg                     bool
		DisabledRepoUnits                       []string
		DefaultRepoUnits                        []string
		DefaultForkRepoUnits                    []string
		PrefixArchiveFiles                      bool
		DisableMigrations                       bool
		DisableStars                            bool `ini:"DISABLE_STARS"`
		DefaultBranch                           string
		AllowAdoptionOfUnadoptedRepositories    bool
		AllowDeleteOfUnadoptedRepositories      bool
		DisableDownloadSourceArchives           bool
		AllowForkWithoutMaximumLimit            bool

		// Repository editor settings
		Editor struct {
			LineWrapExtensions []string
		} `ini:"-"`

		// Repository upload settings
		Upload struct {
			Enabled      bool
			TempPath     string
			AllowedTypes string
			FileMaxSize  int64
			MaxFiles     int
		} `ini:"-"`

		// Repository local settings
		Local struct {
			LocalCopyPath string
		} `ini:"-"`

		// Pull request settings
		PullRequest struct {
			WorkInProgressPrefixes                   []string
			CloseKeywords                            []string
			ReopenKeywords                           []string
			DefaultMergeStyle                        string
			DefaultMergeMessageCommitsLimit          int
			DefaultMergeMessageSize                  int
			DefaultMergeMessageAllAuthors            bool
			DefaultMergeMessageMaxApprovers          int
			DefaultMergeMessageOfficialApproversOnly bool
			PopulateSquashCommentWithCommitMessages  bool
			AddCoCommitterTrailers                   bool
			TestConflictingPatchesWithGitApply       bool
			RetargetChildrenOnMerge                  bool
		} `ini:"repository.pull-request"`

		// Issue Setting
		Issue struct {
			LockReasons []string
			MaxPinned   int
		} `ini:"repository.issue"`

		Release struct {
			AllowedTypes     string
			DefaultPagingNum int
		} `ini:"repository.release"`

		Signing struct {
			SigningKey        string
			SigningName       string
			SigningEmail      string
			InitialCommit     []string
			CRUDActions       []string `ini:"CRUD_ACTIONS"`
			Merges            []string
			Wiki              []string
			DefaultTrustModel string
		} `ini:"repository.signing"`
	}{
		DetectedCharsetsOrder: []string{
			"UTF-8",
			"UTF-16BE",
			"UTF-16LE",
			"UTF-32BE",
			"UTF-32LE",
			"ISO-8859-1",
			"windows-1252",
			"ISO-8859-2",
			"windows-1250",
			"ISO-8859-5",
			"ISO-8859-6",
			"ISO-8859-7",
			"windows-1253",
			"ISO-8859-8-I",
			"windows-1255",
			"ISO-8859-8",
			"windows-1251",
			"windows-1256",
			"KOI8-R",
			"ISO-8859-9",
			"windows-1254",
			"Shift_JIS",
			"GB18030",
			"EUC-JP",
			"EUC-KR",
			"Big5",
			"ISO-2022-JP",
			"ISO-2022-KR",
			"ISO-2022-CN",
			"IBM424_rtl",
			"IBM424_ltr",
			"IBM420_rtl",
			"IBM420_ltr",
		},
		DetectedCharsetScore:                    map[string]int{},
		AnsiCharset:                             "",
		ForcePrivate:                            false,
		DefaultPrivate:                          RepoCreatingLastUserVisibility,
		DefaultPushCreatePrivate:                true,
		MaxCreationLimit:                        -1,
		PreferredLicenses:                       []string{"Apache License 2.0", "MIT License"},
		DisableHTTPGit:                          false,
		AccessControlAllowOrigin:                "",
		UseCompatSSHURI:                         false,
		DefaultCloseIssuesViaCommitsInAnyBranch: false,
		EnablePushCreateUser:                    false,
		EnablePushCreateOrg:                     false,
		DisabledRepoUnits:                       []string{},
		DefaultRepoUnits:                        []string{},
		DefaultForkRepoUnits:                    []string{},
		PrefixArchiveFiles:                      true,
		DisableMigrations:                       false,
		DisableStars:                            false,
		DefaultBranch:                           "main",
		AllowForkWithoutMaximumLimit:            true,

		Editor: struct {
			LineWrapExtensions []string
		}{
			LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,.livemd,", ","),
		},

		Upload: struct {
			Enabled      bool
			TempPath     string
			AllowedTypes string
			FileMaxSize  int64
			MaxFiles     int
		}{
			Enabled:      true,
			TempPath:     "data/tmp/uploads",
			AllowedTypes: "",
			FileMaxSize:  50,
			MaxFiles:     5,
		},

		Local: struct {
			LocalCopyPath string
		}{
			LocalCopyPath: "tmp/local-repo",
		},

		PullRequest: struct {
			WorkInProgressPrefixes                   []string
			CloseKeywords                            []string
			ReopenKeywords                           []string
			DefaultMergeStyle                        string
			DefaultMergeMessageCommitsLimit          int
			DefaultMergeMessageSize                  int
			DefaultMergeMessageAllAuthors            bool
			DefaultMergeMessageMaxApprovers          int
			DefaultMergeMessageOfficialApproversOnly bool
			PopulateSquashCommentWithCommitMessages  bool
			AddCoCommitterTrailers                   bool
			TestConflictingPatchesWithGitApply       bool
			RetargetChildrenOnMerge                  bool
		}{
			WorkInProgressPrefixes: []string{"WIP:", "[WIP]"},

			CloseKeywords:                            strings.Split("close,closes,closed,fix,fixes,fixed,resolve,resolves,resolved", ","),
			ReopenKeywords:                           strings.Split("reopen,reopens,reopened", ","),
			DefaultMergeStyle:                        "merge",
			DefaultMergeMessageCommitsLimit:          50,
			DefaultMergeMessageSize:                  5 * 1024,
			DefaultMergeMessageAllAuthors:            false,
			DefaultMergeMessageMaxApprovers:          10,
			DefaultMergeMessageOfficialApproversOnly: true,
			PopulateSquashCommentWithCommitMessages:  false,
			AddCoCommitterTrailers:                   true,
			RetargetChildrenOnMerge:                  true,
		},

		Issue: struct {
			LockReasons []string
			MaxPinned   int
		}{
			LockReasons: strings.Split("Too heated,Off-topic,Spam,Resolved", ","),
			MaxPinned:   3,
		},

		Release: struct {
			AllowedTypes     string
			DefaultPagingNum int
		}{
			AllowedTypes:     "",
			DefaultPagingNum: 10,
		},

		Signing: struct {
			SigningKey        string
			SigningName       string
			SigningEmail      string
			InitialCommit     []string
			CRUDActions       []string `ini:"CRUD_ACTIONS"`
			Merges            []string
			Wiki              []string
			DefaultTrustModel string
		}{
			SigningKey:        "default",
			SigningName:       "",
			SigningEmail:      "",
			InitialCommit:     []string{"always"},
			CRUDActions:       []string{"pubkey", "twofa", "parentsigned"},
			Merges:            []string{"pubkey", "twofa", "basesigned", "commitssigned"},
			Wiki:              []string{"never"},
			DefaultTrustModel: "collaborator",
		},
	}
	RepoRootPath string
	ScriptType   = "bash"
)

Repository settings

View Source
var (
	// Security settings
	InstallLock                        bool
	SecretKey                          string
	InternalToken                      string // internal access token
	LogInRememberDays                  int
	CookieRememberName                 string
	ReverseProxyAuthUser               string
	ReverseProxyAuthEmail              string
	ReverseProxyAuthFullName           string
	ReverseProxyLimit                  int
	ReverseProxyTrustedProxies         []string
	MinPasswordLength                  int
	ImportLocalPaths                   bool
	DisableGitHooks                    bool
	DisableWebhooks                    bool
	OnlyAllowPushIfGiteaEnvironmentSet bool
	PasswordComplexity                 []string
	PasswordHashAlgo                   string
	PasswordCheckPwn                   bool
	SuccessfulTokensCacheSize          int
	DisableQueryAuthToken              bool
	CSRFCookieName                     = "_csrf"
	CSRFCookieHTTPOnly                 = true
)
View Source
var (
	// AppName is the Application name, used in the page title.
	// It maps to ini:"APP_NAME"
	AppName string
	// AppURL is the Application ROOT_URL. It always has a '/' suffix
	// It maps to ini:"ROOT_URL"
	AppURL string
	// AppSubURL represents the sub-url mounting point for gitea. It is either "" or starts with '/' and ends without '/', such as '/{subpath}'.
	// This value is empty if site does not have sub-url.
	AppSubURL string
	// AppDataPath is the default path for storing data.
	// It maps to ini:"APP_DATA_PATH" in [server] and defaults to AppWorkPath + "/data"
	AppDataPath string
	// LocalURL is the url for locally running applications to contact Gitea. It always has a '/' suffix
	// It maps to ini:"LOCAL_ROOT_URL" in [server]
	LocalURL string
	// AssetVersion holds a opaque value that is used for cache-busting assets
	AssetVersion string

	Protocol                   Scheme
	UseProxyProtocol           bool // `ini:"USE_PROXY_PROTOCOL"`
	ProxyProtocolTLSBridging   bool //`ini:"PROXY_PROTOCOL_TLS_BRIDGING"`
	ProxyProtocolHeaderTimeout time.Duration
	ProxyProtocolAcceptUnknown bool
	Domain                     string
	HTTPAddr                   string
	HTTPPort                   string
	LocalUseProxyProtocol      bool
	RedirectOtherPort          bool
	RedirectorUseProxyProtocol bool
	PortToRedirect             string
	OfflineMode                bool
	CertFile                   string
	KeyFile                    string
	StaticRootPath             string
	StaticCacheTime            time.Duration
	EnableGzip                 bool
	LandingPageURL             LandingPage
	UnixSocketPermission       uint32
	EnablePprof                bool
	PprofDataPath              string
	EnableAcme                 bool
	AcmeTOS                    bool
	AcmeLiveDirectory          string
	AcmeEmail                  string
	AcmeURL                    string
	AcmeCARoot                 string
	SSLMinimumVersion          string
	SSLMaximumVersion          string
	SSLCurvePreferences        []string
	SSLCipherSuites            []string
	GracefulRestartable        bool
	GracefulHammerTime         time.Duration
	StartupTimeout             time.Duration
	PerWriteTimeout            = 30 * time.Second
	PerWritePerKbTimeout       = 10 * time.Second
	StaticURLPrefix            string
	AbsoluteAssetURL           string

	ManifestData string
)
View Source
var (
	// AppVer is the version of the current build of Gitea. It is set in main.go from main.Version.
	AppVer string
	// AppBuiltWith represents a human-readable version go runtime build version and build tags. (See main.go formatBuiltWith().)
	AppBuiltWith string
	// AppStartTime store time gitea has started
	AppStartTime time.Time

	CfgProvider ConfigProvider
	RunMode     string
	RunUser     string
	IsProd      bool
	IsWindows   bool

	// IsInTesting indicates whether the testing is running. A lot of unreliable code causes a lot of nonsense error logs during testing
	// TODO: this is only a temporary solution, we should make the test code more reliable
	IsInTesting = false
)

settings

View Source
var API = struct {
	EnableSwagger          bool
	SwaggerURL             string
	MaxResponseItems       int
	DefaultPagingNum       int
	DefaultGitTreesPerPage int
	DefaultMaxBlobSize     int64
}{
	EnableSwagger:          true,
	SwaggerURL:             "",
	MaxResponseItems:       50,
	DefaultPagingNum:       30,
	DefaultGitTreesPerPage: 1000,
	DefaultMaxBlobSize:     10485760,
}

API settings

View Source
var (
	Actions = struct {
		LogStorage            *Storage // how the created logs should be stored
		ArtifactStorage       *Storage // how the created artifacts should be stored
		ArtifactRetentionDays int64    `ini:"ARTIFACT_RETENTION_DAYS"`
		Enabled               bool
		DefaultActionsURL     defaultActionsURL `ini:"DEFAULT_ACTIONS_URL"`
		ZombieTaskTimeout     time.Duration     `ini:"ZOMBIE_TASK_TIMEOUT"`
		EndlessTaskTimeout    time.Duration     `ini:"ENDLESS_TASK_TIMEOUT"`
		AbandonedJobTimeout   time.Duration     `ini:"ABANDONED_JOB_TIMEOUT"`
		SkipWorkflowStrings   []string          `ìni:"SKIP_WORKFLOW_STRINGS"`
	}{
		Enabled:             true,
		DefaultActionsURL:   defaultActionsURLGitHub,
		SkipWorkflowStrings: []string{"[skip ci]", "[ci skip]", "[no ci]", "[skip actions]", "[actions skip]"},
	}
)

Actions settings

View Source
var Admin struct {
	DisableRegularOrgCreation bool
	DefaultEmailNotification  string
	UserDisabledFeatures      container.Set[string]
}

Admin settings

View Source
var Attachment = struct {
	Storage      *Storage
	AllowedTypes string
	MaxSize      int64
	MaxFiles     int
	Enabled      bool
}{
	Storage:      &Storage{},
	AllowedTypes: ".cpuprofile,.csv,.dmp,.docx,.fodg,.fodp,.fods,.fodt,.gif,.gz,.jpeg,.jpg,.json,.jsonc,.log,.md,.mov,.mp4,.odf,.odg,.odp,.ods,.odt,.patch,.pdf,.png,.pptx,.svg,.tgz,.txt,.webm,.xls,.xlsx,.zip",
	MaxSize:      2048,
	MaxFiles:     5,
	Enabled:      true,
}

Attachment settings

View Source
var CORSConfig = struct {
	Enabled          bool
	AllowDomain      []string // FIXME: this option is from legacy code, it actually works as "AllowedOrigins". When refactoring in the future, the config option should also be renamed together.
	Methods          []string
	MaxAge           time.Duration
	AllowCredentials bool
	Headers          []string
	XFrameOptions    string
}{
	AllowDomain:   []string{"*"},
	Methods:       []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
	Headers:       []string{"Content-Type", "User-Agent"},
	MaxAge:        10 * time.Minute,
	XFrameOptions: "SAMEORIGIN",
}

CORSConfig defines CORS settings

View Source
var CacheService = struct {
	Cache `ini:"cache"`

	LastCommit struct {
		TTL          time.Duration `ini:"ITEM_TTL"`
		CommitsCount int64
	} `ini:"cache.last_commit"`
}{
	Cache: Cache{
		Adapter:  "memory",
		Interval: 60,
		TTL:      16 * time.Hour,
	},
	LastCommit: struct {
		TTL          time.Duration `ini:"ITEM_TTL"`
		CommitsCount int64
	}{
		TTL:          8760 * time.Hour,
		CommitsCount: 1000,
	},
}

CacheService the global cache

View Source
var Camo = struct {
	Enabled   bool
	ServerURL string `ini:"SERVER_URL"`
	HMACKey   string `ini:"HMAC_KEY"`
	Allways   bool
}{}
View Source
var DefaultUILocation = time.Local

DefaultUILocation is the location on the UI, so that we can display the time on UI.

View Source
var DeprecatedWarnings []string

DeprecatedWarnings contains the warning message for various deprecations, including: setting option, file/folder, etc

View Source
var (
	Federation = struct {
		Enabled             bool
		ShareUserStatistics bool
		MaxSize             int64
		Algorithms          []string
		DigestAlgorithm     string
		GetHeaders          []string
		PostHeaders         []string
	}{
		Enabled:             false,
		ShareUserStatistics: true,
		MaxSize:             4,
		Algorithms:          []string{"rsa-sha256", "rsa-sha512", "ed25519"},
		DigestAlgorithm:     "SHA-256",
		GetHeaders:          []string{"(request-target)", "Date"},
		PostHeaders:         []string{"(request-target)", "Date", "Digest"},
	}
)

Federation settings

View Source
var Git = struct {
	Path                 string
	HomePath             string
	DisableDiffHighlight bool

	MaxGitDiffLines           int
	MaxGitDiffLineCharacters  int
	MaxGitDiffFiles           int
	CommitsRangeSize          int // CommitsRangeSize the default commits range size
	BranchesRangeSize         int // BranchesRangeSize the default branches range size
	VerbosePush               bool
	VerbosePushDelay          time.Duration
	GCArgs                    []string `ini:"GC_ARGS" delim:" "`
	EnableAutoGitWireProtocol bool
	PullRequestPushMessage    bool
	LargeObjectThreshold      int64
	DisableCoreProtectNTFS    bool
	DisablePartialClone       bool
	Timeout                   struct {
		Default int
		Migrate int
		Mirror  int
		Clone   int
		Pull    int
		GC      int `ini:"GC"`
	} `ini:"git.timeout"`
}{
	DisableDiffHighlight:      false,
	MaxGitDiffLines:           1000,
	MaxGitDiffLineCharacters:  5000,
	MaxGitDiffFiles:           100,
	CommitsRangeSize:          50,
	BranchesRangeSize:         20,
	VerbosePush:               true,
	VerbosePushDelay:          5 * time.Second,
	GCArgs:                    []string{},
	EnableAutoGitWireProtocol: true,
	PullRequestPushMessage:    true,
	LargeObjectThreshold:      1024 * 1024,
	DisablePartialClone:       false,
	Timeout: struct {
		Default int
		Migrate int
		Mirror  int
		Clone   int
		Pull    int
		GC      int `ini:"GC"`
	}{
		Default: 360,
		Migrate: 600,
		Mirror:  300,
		Clone:   300,
		Pull:    300,
		GC:      60,
	},
}

Git settings

View Source
var GitConfig = GitConfigType{
	Options: make(map[string]string),
}
View Source
var HttpsigAlgs []httpsig.Algorithm

HttpsigAlgs is a constant slice of httpsig algorithm objects

View Source
var IncomingEmail = struct {
	Enabled              bool
	ReplyToAddress       string
	TokenPlaceholder     string `ini:"-"`
	Host                 string
	Port                 int
	UseTLS               bool `ini:"USE_TLS"`
	SkipTLSVerify        bool `ini:"SKIP_TLS_VERIFY"`
	Username             string
	Password             string
	Mailbox              string
	DeleteHandledMessage bool
	MaximumMessageSize   uint32
}{
	Mailbox:              "INBOX",
	DeleteHandledMessage: true,
	TokenPlaceholder:     "%{token}",
	MaximumMessageSize:   10485760,
}
View Source
var Indexer = struct {
	IssueType        string
	IssuePath        string
	IssueConnStr     string
	IssueConnAuth    string
	IssueIndexerName string
	StartupTimeout   time.Duration

	RepoIndexerEnabled   bool
	RepoIndexerRepoTypes []string
	RepoType             string
	RepoPath             string
	RepoConnStr          string
	RepoIndexerName      string
	MaxIndexerFileSize   int64
	IncludePatterns      []glob.Glob
	ExcludePatterns      []glob.Glob
	ExcludeVendored      bool
}{
	IssueType:        "bleve",
	IssuePath:        "indexers/issues.bleve",
	IssueConnStr:     "",
	IssueConnAuth:    "",
	IssueIndexerName: "gitea_issues",

	RepoIndexerEnabled:   false,
	RepoIndexerRepoTypes: []string{"sources", "forks", "mirrors", "templates"},
	RepoType:             "bleve",
	RepoPath:             "indexers/repos.bleve",
	RepoConnStr:          "",
	RepoIndexerName:      "gitea_codes",
	MaxIndexerFileSize:   1024 * 1024,
	ExcludeVendored:      true,
}

Indexer settings

View Source
var LFS = struct {
	StartServer    bool          `ini:"LFS_START_SERVER"`
	JWTSecretBytes []byte        `ini:"-"`
	HTTPAuthExpiry time.Duration `ini:"LFS_HTTP_AUTH_EXPIRY"`
	MaxFileSize    int64         `ini:"LFS_MAX_FILE_SIZE"`
	LocksPagingNum int           `ini:"LFS_LOCKS_PAGING_NUM"`

	Storage *Storage
}{}

LFS represents the configuration for Git LFS

View Source
var Markdown = struct {
	EnableHardLineBreakInComments  bool
	EnableHardLineBreakInDocuments bool
	CustomURLSchemes               []string `ini:"CUSTOM_URL_SCHEMES"`
	FileExtensions                 []string
	EnableMath                     bool
}{
	EnableHardLineBreakInComments:  true,
	EnableHardLineBreakInDocuments: false,
	FileExtensions:                 strings.Split(".md,.markdown,.mdown,.mkd,.livemd", ","),
	EnableMath:                     true,
}

Markdown settings

View Source
var Metrics = struct {
	Enabled                  bool
	Token                    string
	EnabledIssueByLabel      bool
	EnabledIssueByRepository bool
}{
	Enabled:                  false,
	Token:                    "",
	EnabledIssueByLabel:      false,
	EnabledIssueByRepository: false,
}

Metrics settings

View Source
var Migrations = struct {
	MaxAttempts        int
	RetryBackoff       int
	AllowedDomains     string
	BlockedDomains     string
	AllowLocalNetworks bool
	SkipTLSVerify      bool
}{
	MaxAttempts:  3,
	RetryBackoff: 3,
}

Migrations settings

View Source
var MimeTypeMap = struct {
	Enabled bool
	Map     map[string]string
}{
	Enabled: false,
	Map:     map[string]string{},
}

MimeTypeMap defines custom mime type mapping settings

View Source
var Mirror = struct {
	Enabled         bool
	DisableNewPull  bool
	DisableNewPush  bool
	DefaultInterval time.Duration
	MinInterval     time.Duration
}{
	Enabled:         true,
	DisableNewPull:  false,
	DisableNewPush:  false,
	MinInterval:     10 * time.Minute,
	DefaultInterval: 8 * time.Hour,
}

Mirror settings

View Source
var OAuth2 = struct {
	Enabled                    bool
	AccessTokenExpirationTime  int64
	RefreshTokenExpirationTime int64
	InvalidateRefreshTokens    bool
	JWTSigningAlgorithm        string `ini:"JWT_SIGNING_ALGORITHM"`
	JWTSigningPrivateKeyFile   string `ini:"JWT_SIGNING_PRIVATE_KEY_FILE"`
	MaxTokenLength             int
	DefaultApplications        []string
}{
	Enabled:                    true,
	AccessTokenExpirationTime:  3600,
	RefreshTokenExpirationTime: 730,
	InvalidateRefreshTokens:    false,
	JWTSigningAlgorithm:        "RS256",
	JWTSigningPrivateKeyFile:   "jwt/private.pem",
	MaxTokenLength:             math.MaxInt16,
	DefaultApplications:        []string{"git-credential-oauth", "git-credential-manager", "tea"},
}
View Source
var OAuth2Client struct {
	RegisterEmailConfirm   bool
	OpenIDConnectScopes    []string
	EnableAutoRegistration bool
	Username               OAuth2UsernameType
	UpdateAvatar           bool
	AccountLinking         OAuth2AccountLinkingType
}

OAuth2Client settings

View Source
var Other = OtherConfig{
	ShowFooterVersion:          true,
	ShowFooterTemplateLoadTime: true,
	EnableSitemap:              true,
	EnableFeed:                 true,
}
View Source
var (
	Packages = struct {
		Storage           *Storage
		Enabled           bool
		ChunkedUploadPath string
		RegistryHost      string

		LimitTotalOwnerCount int64
		LimitTotalOwnerSize  int64
		LimitSizeAlpine      int64
		LimitSizeCargo       int64
		LimitSizeChef        int64
		LimitSizeComposer    int64
		LimitSizeConan       int64
		LimitSizeConda       int64
		LimitSizeContainer   int64
		LimitSizeCran        int64
		LimitSizeDebian      int64
		LimitSizeGeneric     int64
		LimitSizeGo          int64
		LimitSizeHelm        int64
		LimitSizeMaven       int64
		LimitSizeNpm         int64
		LimitSizeNuGet       int64
		LimitSizePub         int64
		LimitSizePyPI        int64
		LimitSizeRpm         int64
		LimitSizeRubyGems    int64
		LimitSizeSwift       int64
		LimitSizeVagrant     int64
	}{
		Enabled:              true,
		LimitTotalOwnerCount: -1,
	}
)

Package registry settings

View Source
var (
	Project = struct {
		ProjectBoardBasicKanbanType []string
		ProjectBoardBugTriageType   []string
	}{
		ProjectBoardBasicKanbanType: []string{"To Do", "In Progress", "Done"},
		ProjectBoardBugTriageType:   []string{"Needs Triage", "High Priority", "Low Priority", "Closed"},
	}
)

Project settings

View Source
var Proxy = struct {
	Enabled       bool
	ProxyURL      string
	ProxyURLFixed *url.URL
	ProxyHosts    []string
}{
	Enabled:    false,
	ProxyURL:   "",
	ProxyHosts: []string{},
}

Proxy settings

View Source
var RepoArchive = struct {
	Storage *Storage
}{}
View Source
var SSH = struct {
	Disabled                              bool               `ini:"DISABLE_SSH"`
	StartBuiltinServer                    bool               `ini:"START_SSH_SERVER"`
	BuiltinServerUser                     string             `ini:"BUILTIN_SSH_SERVER_USER"`
	UseProxyProtocol                      bool               `ini:"SSH_SERVER_USE_PROXY_PROTOCOL"`
	Domain                                string             `ini:"SSH_DOMAIN"`
	Port                                  int                `ini:"SSH_PORT"`
	User                                  string             `ini:"SSH_USER"`
	ListenHost                            string             `ini:"SSH_LISTEN_HOST"`
	ListenPort                            int                `ini:"SSH_LISTEN_PORT"`
	RootPath                              string             `ini:"SSH_ROOT_PATH"`
	ServerCiphers                         []string           `ini:"SSH_SERVER_CIPHERS"`
	ServerKeyExchanges                    []string           `ini:"SSH_SERVER_KEY_EXCHANGES"`
	ServerMACs                            []string           `ini:"SSH_SERVER_MACS"`
	ServerHostKeys                        []string           `ini:"SSH_SERVER_HOST_KEYS"`
	KeyTestPath                           string             `ini:"SSH_KEY_TEST_PATH"`
	KeygenPath                            string             `ini:"SSH_KEYGEN_PATH"`
	AuthorizedKeysBackup                  bool               `ini:"SSH_AUTHORIZED_KEYS_BACKUP"`
	AuthorizedPrincipalsBackup            bool               `ini:"SSH_AUTHORIZED_PRINCIPALS_BACKUP"`
	AuthorizedKeysCommandTemplate         string             `ini:"SSH_AUTHORIZED_KEYS_COMMAND_TEMPLATE"`
	AuthorizedKeysCommandTemplateTemplate *template.Template `ini:"-"`
	MinimumKeySizeCheck                   bool               `ini:"-"`
	MinimumKeySizes                       map[string]int     `ini:"-"`
	CreateAuthorizedKeysFile              bool               `ini:"SSH_CREATE_AUTHORIZED_KEYS_FILE"`
	CreateAuthorizedPrincipalsFile        bool               `ini:"SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE"`
	ExposeAnonymous                       bool               `ini:"SSH_EXPOSE_ANONYMOUS"`
	AuthorizedPrincipalsAllow             []string           `ini:"SSH_AUTHORIZED_PRINCIPALS_ALLOW"`
	AuthorizedPrincipalsEnabled           bool               `ini:"-"`
	TrustedUserCAKeys                     []string           `ini:"SSH_TRUSTED_USER_CA_KEYS"`
	TrustedUserCAKeysFile                 string             `ini:"SSH_TRUSTED_USER_CA_KEYS_FILENAME"`
	TrustedUserCAKeysParsed               []gossh.PublicKey  `ini:"-"`
	PerWriteTimeout                       time.Duration      `ini:"SSH_PER_WRITE_TIMEOUT"`
	PerWritePerKbTimeout                  time.Duration      `ini:"SSH_PER_WRITE_PER_KB_TIMEOUT"`
}{
	Disabled:                      false,
	StartBuiltinServer:            false,
	Domain:                        "",
	Port:                          22,
	ServerCiphers:                 []string{"chacha20-poly1305@openssh.com", "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "aes256-gcm@openssh.com"},
	ServerKeyExchanges:            []string{"curve25519-sha256", "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "diffie-hellman-group14-sha256", "diffie-hellman-group14-sha1"},
	ServerMACs:                    []string{"hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1"},
	KeygenPath:                    "",
	MinimumKeySizeCheck:           true,
	MinimumKeySizes:               map[string]int{"ed25519": 256, "ed25519-sk": 256, "ecdsa": 256, "ecdsa-sk": 256, "rsa": 3071},
	ServerHostKeys:                []string{"ssh/gitea.rsa", "ssh/gogs.rsa"},
	AuthorizedKeysCommandTemplate: "{{.AppPath}} --config={{.CustomConf}} serv key-{{.Key.ID}}",
	PerWriteTimeout:               PerWriteTimeout,
	PerWritePerKbTimeout:          PerWritePerKbTimeout,
}
View Source
var Service = struct {
	DefaultUserVisibility                   string
	DefaultUserVisibilityMode               structs.VisibleType
	AllowedUserVisibilityModes              []string
	AllowedUserVisibilityModesSlice         AllowedVisibility `ini:"-"`
	DefaultOrgVisibility                    string
	DefaultOrgVisibilityMode                structs.VisibleType
	ActiveCodeLives                         int
	ResetPwdCodeLives                       int
	RegisterEmailConfirm                    bool
	RegisterManualConfirm                   bool
	EmailDomainAllowList                    []glob.Glob
	EmailDomainBlockList                    []glob.Glob
	DisableRegistration                     bool
	AllowOnlyInternalRegistration           bool
	AllowOnlyExternalRegistration           bool
	ShowRegistrationButton                  bool
	ShowMilestonesDashboardPage             bool
	RequireSignInView                       bool
	EnableNotifyMail                        bool
	EnableBasicAuth                         bool
	EnableReverseProxyAuth                  bool
	EnableReverseProxyAuthAPI               bool
	EnableReverseProxyAutoRegister          bool
	EnableReverseProxyEmail                 bool
	EnableReverseProxyFullName              bool
	EnableCaptcha                           bool
	RequireCaptchaForLogin                  bool
	RequireExternalRegistrationCaptcha      bool
	RequireExternalRegistrationPassword     bool
	CaptchaType                             string
	RecaptchaSecret                         string
	RecaptchaSitekey                        string
	RecaptchaURL                            string
	CfTurnstileSecret                       string
	CfTurnstileSitekey                      string
	HcaptchaSecret                          string
	HcaptchaSitekey                         string
	McaptchaSecret                          string
	McaptchaSitekey                         string
	McaptchaURL                             string
	DefaultKeepEmailPrivate                 bool
	DefaultAllowCreateOrganization          bool
	DefaultUserIsRestricted                 bool
	EnableTimetracking                      bool
	DefaultEnableTimetracking               bool
	DefaultEnableDependencies               bool
	AllowCrossRepositoryDependencies        bool
	DefaultAllowOnlyContributorsToTrackTime bool
	NoReplyAddress                          string
	UserLocationMapURL                      string
	EnableUserHeatmap                       bool
	AutoWatchNewRepos                       bool
	AutoWatchOnChanges                      bool
	DefaultOrgMemberVisible                 bool
	UserDeleteWithCommentsMaxTime           time.Duration
	ValidSiteURLSchemes                     []string

	// OpenID settings
	EnableOpenIDSignIn bool
	EnableOpenIDSignUp bool
	OpenIDWhitelist    []*regexp.Regexp
	OpenIDBlacklist    []*regexp.Regexp

	// Explore page settings
	Explore struct {
		RequireSigninView bool `ini:"REQUIRE_SIGNIN_VIEW"`
		DisableUsersPage  bool `ini:"DISABLE_USERS_PAGE"`
	} `ini:"service.explore"`
}{
	AllowedUserVisibilityModesSlice: []bool{true, true, true},
}

Service settings

View Source
var SessionConfig = struct {
	OriginalProvider string
	Provider         string
	// Provider configuration, it's corresponding to provider.
	ProviderConfig string
	// Cookie name to save session ID. Default is "MacaronSession".
	CookieName string
	// Cookie path to store. Default is "/".
	CookiePath string
	// GC interval time in seconds. Default is 3600.
	Gclifetime int64
	// Max life time in seconds. Default is whatever GC interval time is.
	Maxlifetime int64
	// Use HTTPS only. Default is false.
	Secure bool
	// Cookie domain name. Default is empty.
	Domain string
	// SameSite declares if your cookie should be restricted to a first-party or same-site context. Valid strings are "none", "lax", "strict". Default is "lax"
	SameSite http.SameSite
}{
	CookieName:  "i_like_gitea",
	Gclifetime:  86400,
	Maxlifetime: 86400,
	SameSite:    http.SameSiteLaxMode,
}

SessionConfig defines Session settings

View Source
var UI = struct {
	ExplorePagingNum        int
	SitemapPagingNum        int
	IssuePagingNum          int
	RepoSearchPagingNum     int
	MembersPagingNum        int
	FeedMaxCommitNum        int
	FeedPagingNum           int
	PackagesPagingNum       int
	GraphMaxCommitNum       int
	CodeCommentLines        int
	ReactionMaxUserNum      int
	MaxDisplayFileSize      int64
	ShowUserEmail           bool
	DefaultShowFullName     bool
	DefaultTheme            string
	Themes                  []string
	Reactions               []string
	ReactionsLookup         container.Set[string] `ini:"-"`
	CustomEmojis            []string
	CustomEmojisMap         map[string]string `ini:"-"`
	SearchRepoDescription   bool
	OnlyShowRelevantRepos   bool
	ExploreDefaultSort      string `ini:"EXPLORE_PAGING_DEFAULT_SORT"`
	PreferredTimestampTense string

	AmbiguousUnicodeDetection bool

	Notification struct {
		MinTimeout            time.Duration
		TimeoutStep           time.Duration
		MaxTimeout            time.Duration
		EventSourceUpdateTime time.Duration
	} `ini:"ui.notification"`

	SVG struct {
		Enabled bool `ini:"ENABLE_RENDER"`
	} `ini:"ui.svg"`

	CSV struct {
		MaxFileSize int64
	} `ini:"ui.csv"`

	Admin struct {
		UserPagingNum   int
		RepoPagingNum   int
		NoticePagingNum int
		OrgPagingNum    int
	} `ini:"ui.admin"`
	User struct {
		RepoPagingNum int
	} `ini:"ui.user"`
	Meta struct {
		Author      string
		Description string
		Keywords    string
	} `ini:"ui.meta"`
}{
	ExplorePagingNum:        20,
	SitemapPagingNum:        20,
	IssuePagingNum:          20,
	RepoSearchPagingNum:     20,
	MembersPagingNum:        20,
	FeedMaxCommitNum:        5,
	FeedPagingNum:           20,
	PackagesPagingNum:       20,
	GraphMaxCommitNum:       100,
	CodeCommentLines:        4,
	ReactionMaxUserNum:      10,
	MaxDisplayFileSize:      8388608,
	DefaultTheme:            `gitea-auto`,
	Themes:                  []string{`gitea-auto`, `gitea-light`, `gitea-dark`},
	Reactions:               []string{`+1`, `-1`, `laugh`, `hooray`, `confused`, `heart`, `rocket`, `eyes`},
	CustomEmojis:            []string{`git`, `gitea`, `codeberg`, `gitlab`, `github`, `gogs`},
	CustomEmojisMap:         map[string]string{"git": ":git:", "gitea": ":gitea:", "codeberg": ":codeberg:", "gitlab": ":gitlab:", "github": ":github:", "gogs": ":gogs:"},
	PreferredTimestampTense: "mixed",

	AmbiguousUnicodeDetection: true,

	Notification: struct {
		MinTimeout            time.Duration
		TimeoutStep           time.Duration
		MaxTimeout            time.Duration
		EventSourceUpdateTime time.Duration
	}{
		MinTimeout:            10 * time.Second,
		TimeoutStep:           10 * time.Second,
		MaxTimeout:            60 * time.Second,
		EventSourceUpdateTime: 10 * time.Second,
	},
	SVG: struct {
		Enabled bool `ini:"ENABLE_RENDER"`
	}{
		Enabled: true,
	},
	CSV: struct {
		MaxFileSize int64
	}{
		MaxFileSize: 524288,
	},
	Admin: struct {
		UserPagingNum   int
		RepoPagingNum   int
		NoticePagingNum int
		OrgPagingNum    int
	}{
		UserPagingNum:   50,
		RepoPagingNum:   50,
		NoticePagingNum: 25,
		OrgPagingNum:    50,
	},
	User: struct {
		RepoPagingNum int
	}{
		RepoPagingNum: 15,
	},
	Meta: struct {
		Author      string
		Description string
		Keywords    string
	}{
		Author:      "Gitea - Git with a cup of tea",
		Description: "Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go",
		Keywords:    "go,git,self-hosted,gitea",
	},
}

UI settings

View Source
var Webhook = struct {
	QueueLength     int
	DeliverTimeout  int
	SkipTLSVerify   bool
	AllowedHostList string
	Types           []string
	PagingNum       int
	ProxyURL        string
	ProxyURLFixed   *url.URL
	ProxyHosts      []string
}{
	QueueLength:    1000,
	DeliverTimeout: 5,
	SkipTLSVerify:  false,
	PagingNum:      10,
	ProxyURL:       "",
	ProxyHosts:     []string{},
}

Webhook settings

Functions

func ClearEnvConfigKeys added in v1.20.0

func ClearEnvConfigKeys()

func CollectEnvConfigKeys added in v1.20.0

func CollectEnvConfigKeys() (keys []string)

func CompileEmailGlobList added in v1.20.0

func CompileEmailGlobList(sec ConfigSection, keys ...string) (globs []glob.Glob)

func ConfigInheritedKeyString added in v1.20.0

func ConfigInheritedKeyString(sec ConfigSection, key string, def ...string) string

func ConfigSectionKeyBool added in v1.20.0

func ConfigSectionKeyBool(sec ConfigSection, key string, def ...bool) bool

func ConfigSectionKeyString added in v1.20.0

func ConfigSectionKeyString(sec ConfigSection, key string, def ...string) string

func DBConnStr added in v1.10.0

func DBConnStr() (string, error)

DBConnStr returns database connection string

func EnvironmentToConfig added in v1.20.0

func EnvironmentToConfig(cfg ConfigProvider, envs []string) (changed bool)

func GetCronSettings added in v1.12.0

func GetCronSettings(name string, config any) (any, error)

GetCronSettings maps the cron subsection to the provided config

func GetDefaultDisableGravatar added in v1.17.4

func GetDefaultDisableGravatar() bool

func GetDefaultEnableFederatedAvatar added in v1.17.4

func GetDefaultEnableFederatedAvatar(disableGravatar bool) bool

func GetGeneralTokenSigningSecret added in v1.21.6

func GetGeneralTokenSigningSecret() []byte

func GetHighlightMapping added in v1.19.0

func GetHighlightMapping() map[string]string

func HasInstallLock added in v1.20.0

func HasInstallLock(rootCfg ConfigProvider) bool

HasInstallLock checks the install-lock in ConfigProvider directly, because sometimes the config file is not loaded into setting variables yet.

func IndexerGlobFromString added in v1.10.0

func IndexerGlobFromString(globstr string) []glob.Glob

IndexerGlobFromString parses a comma separated list of patterns and returns a glob.Glob slice suited for repo indexing

func InitCfgProvider added in v1.20.0

func InitCfgProvider(file string)

func InitLoggersForTest added in v1.20.0

func InitLoggersForTest()

func InitSQLLoggersForCli added in v1.20.0

func InitSQLLoggersForCli(level log.Level)

func InitWorkPathAndCfgProvider added in v1.20.0

func InitWorkPathAndCfgProvider(getEnvFn func(name string) string, args ArgWorkPathAndCustomConf)

InitWorkPathAndCfgProvider will set AppWorkPath, CustomPath and CustomConf, init default config provider by CustomConf

func InitWorkPathAndCommonConfig added in v1.20.0

func InitWorkPathAndCommonConfig(getEnvFn func(name string) string, args ArgWorkPathAndCustomConf)

InitWorkPathAndCommonConfig will set AppWorkPath, CustomPath and CustomConf, init default config provider by CustomConf and load common settings,

func IsAccessLogEnabled added in v1.20.0

func IsAccessLogEnabled() bool

func IsRouteLogEnabled added in v1.20.0

func IsRouteLogEnabled() bool

func IsRunUserMatchCurrentUser

func IsRunUserMatchCurrentUser(runUser string) (string, bool)

IsRunUserMatchCurrentUser returns false if configured run user does not match actual user that runs the app. The first return value is the actual user name. This check is ignored under Windows since SSH remote login is not the main method to login on Windows.

func IsValidStorageType added in v1.20.0

func IsValidStorageType(storageType StorageType) bool

IsValidStorageType returns true if the given storage type is valid

func LastCommitCacheTTLSeconds added in v1.14.0

func LastCommitCacheTTLSeconds() int64

LastCommitCacheTTLSeconds returns the TTLSeconds or unix timestamp for memcache

func LoadCommonSettings added in v1.19.0

func LoadCommonSettings()

func LoadDBSetting added in v1.19.0

func LoadDBSetting()

LoadDBSetting loads the database settings

func LoadQueueSettings added in v1.19.0

func LoadQueueSettings()

func LoadSettings added in v1.19.0

func LoadSettings()

LoadSettings initializes the settings for normal start up

func LoadSettingsForInstall added in v1.19.0

func LoadSettingsForInstall()

LoadSettingsForInstall initializes the settings for install

func LogPrepareFilenameForWriter added in v1.20.0

func LogPrepareFilenameForWriter(fileName, defaultFileName string) string

func MakeAbsoluteAssetURL added in v1.14.0

func MakeAbsoluteAssetURL(appURL, staticURLPrefix string) string

MakeAbsoluteAssetURL returns the absolute asset url prefix without a trailing slash

func MakeManifestData added in v1.14.0

func MakeManifestData(appName, appURL, absoluteAssetURL string) []byte

MakeManifestData generates web app manifest JSON

func MustInstalled added in v1.20.0

func MustInstalled()

func ParseMSSQLHostPort added in v1.10.0

func ParseMSSQLHostPort(info string) (string, string)

ParseMSSQLHostPort splits the host into host and port

func PrepareAppDataPath added in v1.16.0

func PrepareAppDataPath() error

PrepareAppDataPath creates app data directory if necessary

func RestartLogsWithPIDSuffix added in v1.11.0

func RestartLogsWithPIDSuffix()

RestartLogsWithPIDSuffix restarts the logs with a PID suffix on files FIXME: it seems not right, it breaks log rotating or log collectors

Types

type AllowedVisibility added in v1.15.0

type AllowedVisibility []bool

AllowedVisibility store in a 3 item bool array what is allowed

func (AllowedVisibility) IsAllowedVisibility added in v1.15.0

func (a AllowedVisibility) IsAllowedVisibility(t structs.VisibleType) bool

IsAllowedVisibility check if a AllowedVisibility allow a specific VisibleType

func (AllowedVisibility) ToVisibleTypeSlice added in v1.15.0

func (a AllowedVisibility) ToVisibleTypeSlice() (result []structs.VisibleType)

ToVisibleTypeSlice convert a AllowedVisibility into a VisibleType slice

type ArgWorkPathAndCustomConf added in v1.20.0

type ArgWorkPathAndCustomConf struct {
	WorkPath   string
	CustomPath string
	CustomConf string
}

type Cache added in v1.3.0

type Cache struct {
	Adapter  string
	Interval int
	Conn     string
	TTL      time.Duration `ini:"ITEM_TTL"`
}

Cache represents cache settings

func (Cache) TTLSeconds added in v1.14.0

func (c Cache) TTLSeconds() int64

TTLSeconds returns the TTLSeconds or unix timestamp for memcache

type ConfigKey added in v1.20.0

type ConfigKey interface {
	Name() string
	Value() string
	SetValue(v string)

	In(defaultVal string, candidates []string) string
	String() string
	Strings(delim string) []string

	MustString(defaultVal string) string
	MustBool(defaultVal ...bool) bool
	MustInt(defaultVal ...int) int
	MustInt64(defaultVal ...int64) int64
	MustDuration(defaultVal ...time.Duration) time.Duration
}

func ConfigInheritedKey added in v1.20.0

func ConfigInheritedKey(sec ConfigSection, key string) ConfigKey

ConfigInheritedKey works like ini.Section.Key(), but it always returns a new key instance, it is O(n) because NewKey is O(n) and the returned key is safe to be used with "MustXxx", it doesn't change the parent's values. Otherwise, ini.Section.Key().MustXxx would pollute the parent section's keys. It never returns nil.

func ConfigSectionKey added in v1.20.0

func ConfigSectionKey(sec ConfigSection, key string) ConfigKey

ConfigSectionKey only searches the keys in the given section, but it is O(n). ini package has a special behavior: with "[sec] a=1" and an empty "[sec.sub]", then in "[sec.sub]", Key()/HasKey() can always see "a=1" because it always tries parent sections. It returns nil if the key doesn't exist.

type ConfigProvider added in v1.19.0

type ConfigProvider interface {
	Section(section string) ConfigSection
	Sections() []ConfigSection
	NewSection(name string) (ConfigSection, error)
	GetSection(name string) (ConfigSection, error)
	Save() error
	SaveTo(filename string) error

	DisableSaving()
	PrepareSaving() (ConfigProvider, error)
	IsLoadedFromEmpty() bool
}

ConfigProvider represents a config provider

func NewConfigProviderForLocale added in v1.20.0

func NewConfigProviderForLocale(source any, others ...any) (ConfigProvider, error)

NewConfigProviderForLocale loads locale configuration from source and others. "string" if for a local file path, "[]byte" is for INI content

func NewConfigProviderFromData added in v1.20.0

func NewConfigProviderFromData(configContent string) (ConfigProvider, error)

NewConfigProviderFromData this function is mainly for testing purpose

func NewConfigProviderFromFile added in v1.20.0

func NewConfigProviderFromFile(file string) (ConfigProvider, error)

NewConfigProviderFromFile load configuration from file. NOTE: do not print any log except error.

type ConfigSection added in v1.20.0

type ConfigSection interface {
	Name() string
	MapTo(any) error
	HasKey(key string) bool
	NewKey(name, value string) (ConfigKey, error)
	Key(key string) ConfigKey
	Keys() []ConfigKey
	ChildSections() []ConfigSection
}

type ConfigStruct added in v1.21.0

type ConfigStruct struct {
	Picture    *PictureStruct
	Repository *RepositoryStruct
}

func Config added in v1.21.0

func Config() *ConfigStruct

type DatabaseType added in v1.19.0

type DatabaseType string

func (DatabaseType) IsMSSQL added in v1.19.0

func (t DatabaseType) IsMSSQL() bool

func (DatabaseType) IsMySQL added in v1.19.0

func (t DatabaseType) IsMySQL() bool

func (DatabaseType) IsPostgreSQL added in v1.19.0

func (t DatabaseType) IsPostgreSQL() bool

func (DatabaseType) IsSQLite3 added in v1.19.0

func (t DatabaseType) IsSQLite3() bool

func (DatabaseType) String added in v1.19.0

func (t DatabaseType) String() string

type GitConfigType added in v1.20.0

type GitConfigType struct {
	Options map[string]string // git config key is case-insensitive, always use lower-case
}

func (*GitConfigType) GetOption added in v1.20.0

func (c *GitConfigType) GetOption(key string) string

func (*GitConfigType) SetOption added in v1.20.0

func (c *GitConfigType) SetOption(key, val string)

type LandingPage

type LandingPage string

LandingPage describes the default page

const (
	LandingPageHome          LandingPage = "/"
	LandingPageExplore       LandingPage = "/explore"
	LandingPageOrganizations LandingPage = "/explore/organizations"
	LandingPageLogin         LandingPage = "/user/login"
)

enumerates all the landing page types

type LogGlobalConfig added in v1.20.0

type LogGlobalConfig struct {
	RootPath string

	Mode               string
	Level              log.Level
	StacktraceLogLevel log.Level
	BufferLen          int

	EnableSSHLog bool

	AccessLogTemplate string
	RequestIDHeaders  []string
}
var Log LogGlobalConfig

type Mailer

type Mailer struct {
	// Mailer
	Name                 string `ini:"NAME"`
	From                 string `ini:"FROM"`
	EnvelopeFrom         string `ini:"ENVELOPE_FROM"`
	OverrideEnvelopeFrom bool   `ini:"-"`
	FromName             string `ini:"-"`
	FromEmail            string `ini:"-"`
	SendAsPlainText      bool   `ini:"SEND_AS_PLAIN_TEXT"`
	SubjectPrefix        string `ini:"SUBJECT_PREFIX"`

	// SMTP sender
	Protocol             string `ini:"PROTOCOL"`
	SMTPAddr             string `ini:"SMTP_ADDR"`
	SMTPPort             string `ini:"SMTP_PORT"`
	User                 string `ini:"USER"`
	Passwd               string `ini:"PASSWD"`
	EnableHelo           bool   `ini:"ENABLE_HELO"`
	HeloHostname         string `ini:"HELO_HOSTNAME"`
	ForceTrustServerCert bool   `ini:"FORCE_TRUST_SERVER_CERT"`
	UseClientCert        bool   `ini:"USE_CLIENT_CERT"`
	ClientCertFile       string `ini:"CLIENT_CERT_FILE"`
	ClientKeyFile        string `ini:"CLIENT_KEY_FILE"`

	// Sendmail sender
	SendmailPath        string        `ini:"SENDMAIL_PATH"`
	SendmailArgs        []string      `ini:"-"`
	SendmailTimeout     time.Duration `ini:"SENDMAIL_TIMEOUT"`
	SendmailConvertCRLF bool          `ini:"SENDMAIL_CONVERT_CRLF"`
}

Mailer represents mail service.

var MailService *Mailer

MailService the global mailer

type MarkupRenderer added in v1.15.0

type MarkupRenderer struct {
	Enabled              bool
	MarkupName           string
	Command              string
	FileExtensions       []string
	IsInputFile          bool
	NeedPostProcess      bool
	MarkupSanitizerRules []MarkupSanitizerRule
	RenderContentMode    string
}

MarkupRenderer defines the external parser configured in ini

type MarkupSanitizerRule added in v1.11.0

type MarkupSanitizerRule struct {
	Element            string
	AllowAttr          string
	Regexp             *regexp.Regexp
	AllowDataURIImages bool
}

MarkupSanitizerRule defines the policy for whitelisting attributes on certain elements.

type MinioStorageConfig added in v1.20.0

type MinioStorageConfig struct {
	Endpoint           string `ini:"MINIO_ENDPOINT" json:",omitempty"`
	AccessKeyID        string `ini:"MINIO_ACCESS_KEY_ID" json:",omitempty"`
	SecretAccessKey    string `ini:"MINIO_SECRET_ACCESS_KEY" json:",omitempty"`
	Bucket             string `ini:"MINIO_BUCKET" json:",omitempty"`
	Location           string `ini:"MINIO_LOCATION" json:",omitempty"`
	BasePath           string `ini:"MINIO_BASE_PATH" json:",omitempty"`
	UseSSL             bool   `ini:"MINIO_USE_SSL"`
	InsecureSkipVerify bool   `ini:"MINIO_INSECURE_SKIP_VERIFY"`
	ChecksumAlgorithm  string `ini:"MINIO_CHECKSUM_ALGORITHM" json:",omitempty"`
	ServeDirect        bool   `ini:"SERVE_DIRECT"`
}

MinioStorageConfig represents the configuration for a minio storage

type OAuth2AccountLinkingType added in v1.15.0

type OAuth2AccountLinkingType string

OAuth2AccountLinkingType is enum describing behaviour of linking with existing account

const (
	// OAuth2AccountLinkingDisabled error will be displayed if account exist
	OAuth2AccountLinkingDisabled OAuth2AccountLinkingType = "disabled"
	// OAuth2AccountLinkingLogin account linking login will be displayed if account exist
	OAuth2AccountLinkingLogin OAuth2AccountLinkingType = "login"
	// OAuth2AccountLinkingAuto account will be automatically linked if account exist
	OAuth2AccountLinkingAuto OAuth2AccountLinkingType = "auto"
)

type OAuth2UsernameType added in v1.15.0

type OAuth2UsernameType string

OAuth2UsernameType is enum describing the way gitea 'name' should be generated from oauth2 data

const (
	// OAuth2UsernameUserid oauth2 userid field will be used as gitea name
	OAuth2UsernameUserid OAuth2UsernameType = "userid"
	// OAuth2UsernameNickname oauth2 nickname field will be used as gitea name
	OAuth2UsernameNickname OAuth2UsernameType = "nickname"
	// OAuth2UsernameEmail username of oauth2 email field will be used as gitea name
	OAuth2UsernameEmail OAuth2UsernameType = "email"
)

type OpenWithEditorApp added in v1.22.0

type OpenWithEditorApp struct {
	DisplayName string
	OpenURL     string
}

type OpenWithEditorAppsType added in v1.22.0

type OpenWithEditorAppsType []OpenWithEditorApp

func DefaultOpenWithEditorApps added in v1.22.0

func DefaultOpenWithEditorApps() OpenWithEditorAppsType

func (OpenWithEditorAppsType) ToTextareaString added in v1.22.0

func (t OpenWithEditorAppsType) ToTextareaString() string

type OtherConfig added in v1.20.0

type OtherConfig struct {
	ShowFooterVersion          bool
	ShowFooterTemplateLoadTime bool
	EnableFeed                 bool
	EnableSitemap              bool
}

type PictureStruct added in v1.21.0

type PictureStruct struct {
	DisableGravatar       *config.Value[bool]
	EnableFederatedAvatar *config.Value[bool]
}

type QueueSettings added in v1.11.0

type QueueSettings struct {
	Name string // not an INI option, it is the name for [queue.the-name] section

	Type    string
	Datadir string
	ConnStr string // for leveldb or redis
	Length  int    // max queue length before blocking

	QueueName, SetName string // the name suffix for storage (db key, redis key), "set" is for unique queue

	BatchLength int
	MaxWorkers  int
}

QueueSettings represent the settings for a queue from the ini

func GetQueueSettings added in v1.11.0

func GetQueueSettings(rootCfg ConfigProvider, name string) (QueueSettings, error)

type RepositoryStruct added in v1.22.0

type RepositoryStruct struct {
	OpenWithEditorApps *config.Value[OpenWithEditorAppsType]
}

type Scheme

type Scheme string

Scheme describes protocol types

const (
	HTTP     Scheme = "http"
	HTTPS    Scheme = "https"
	FCGI     Scheme = "fcgi"
	FCGIUnix Scheme = "fcgi+unix"
	HTTPUnix Scheme = "http+unix"
)

enumerates all the scheme types

type Storage added in v1.13.0

type Storage struct {
	Type          StorageType        // local or minio
	Path          string             `json:",omitempty"` // for local type
	TemporaryPath string             `json:",omitempty"`
	MinioConfig   MinioStorageConfig // for minio type
}

Storage represents configuration of storages

func (*Storage) ToShadowCopy added in v1.20.0

func (storage *Storage) ToShadowCopy() Storage

type StorageType added in v1.20.0

type StorageType string

StorageType is a type of Storage

const (
	// LocalStorageType is the type descriptor for local storage
	LocalStorageType StorageType = "local"
	// MinioStorageType is the type descriptor for minio storage
	MinioStorageType StorageType = "minio"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL