1// Copyright 2019 The Gitea Authors. All rights reserved.
2// Use of this source code is governed by a MIT-style
3// license that can be found in the LICENSE file.
4
5package models
6
7import (
8	"fmt"
9	"os"
10	"strings"
11
12	repo_model "code.gitea.io/gitea/models/repo"
13	user_model "code.gitea.io/gitea/models/user"
14	"code.gitea.io/gitea/modules/setting"
15)
16
17// env keys for git hooks need
18const (
19	EnvRepoName     = "GITEA_REPO_NAME"
20	EnvRepoUsername = "GITEA_REPO_USER_NAME"
21	EnvRepoID       = "GITEA_REPO_ID"
22	EnvRepoIsWiki   = "GITEA_REPO_IS_WIKI"
23	EnvPusherName   = "GITEA_PUSHER_NAME"
24	EnvPusherEmail  = "GITEA_PUSHER_EMAIL"
25	EnvPusherID     = "GITEA_PUSHER_ID"
26	EnvKeyID        = "GITEA_KEY_ID" // public key ID
27	EnvDeployKeyID  = "GITEA_DEPLOY_KEY_ID"
28	EnvPRID         = "GITEA_PR_ID"
29	EnvIsInternal   = "GITEA_INTERNAL_PUSH"
30	EnvAppURL       = "GITEA_ROOT_URL"
31)
32
33// InternalPushingEnvironment returns an os environment to switch off hooks on push
34// It is recommended to avoid using this unless you are pushing within a transaction
35// or if you absolutely are sure that post-receive and pre-receive will do nothing
36// We provide the full pushing-environment for other hook providers
37func InternalPushingEnvironment(doer *user_model.User, repo *repo_model.Repository) []string {
38	return append(PushingEnvironment(doer, repo),
39		EnvIsInternal+"=true",
40	)
41}
42
43// PushingEnvironment returns an os environment to allow hooks to work on push
44func PushingEnvironment(doer *user_model.User, repo *repo_model.Repository) []string {
45	return FullPushingEnvironment(doer, doer, repo, repo.Name, 0)
46}
47
48// FullPushingEnvironment returns an os environment to allow hooks to work on push
49func FullPushingEnvironment(author, committer *user_model.User, repo *repo_model.Repository, repoName string, prID int64) []string {
50	isWiki := "false"
51	if strings.HasSuffix(repoName, ".wiki") {
52		isWiki = "true"
53	}
54
55	authorSig := author.NewGitSig()
56	committerSig := committer.NewGitSig()
57
58	environ := append(os.Environ(),
59		"GIT_AUTHOR_NAME="+authorSig.Name,
60		"GIT_AUTHOR_EMAIL="+authorSig.Email,
61		"GIT_COMMITTER_NAME="+committerSig.Name,
62		"GIT_COMMITTER_EMAIL="+committerSig.Email,
63		EnvRepoName+"="+repoName,
64		EnvRepoUsername+"="+repo.OwnerName,
65		EnvRepoIsWiki+"="+isWiki,
66		EnvPusherName+"="+committer.Name,
67		EnvPusherID+"="+fmt.Sprintf("%d", committer.ID),
68		EnvRepoID+"="+fmt.Sprintf("%d", repo.ID),
69		EnvPRID+"="+fmt.Sprintf("%d", prID),
70		EnvAppURL+"="+setting.AppURL,
71		"SSH_ORIGINAL_COMMAND=gitea-internal",
72	)
73
74	if !committer.KeepEmailPrivate {
75		environ = append(environ, EnvPusherEmail+"="+committer.Email)
76	}
77
78	return environ
79}
80