1// Copyright 2021 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
5// Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead.
6package private
7
8import (
9	"context"
10	"fmt"
11	"net/http"
12
13	repo_model "code.gitea.io/gitea/models/repo"
14	gitea_context "code.gitea.io/gitea/modules/context"
15	"code.gitea.io/gitea/modules/git"
16	"code.gitea.io/gitea/modules/log"
17)
18
19// __________
20// \______   \ ____ ______   ____
21//  |       _// __ \\____ \ /  _ \
22//  |    |   \  ___/|  |_> >  <_> )
23//  |____|_  /\___  >   __/ \____/
24//         \/     \/|__|
25//    _____                .__                                     __
26//   /  _  \   ______ _____|__| ____   ____   _____   ____   _____/  |_
27//  /  /_\  \ /  ___//  ___/  |/ ___\ /    \ /     \_/ __ \ /    \   __\
28// /    |    \\___ \ \___ \|  / /_/  >   |  \  Y Y  \  ___/|   |  \  |
29// \____|__  /____  >____  >__\___  /|___|  /__|_|  /\___  >___|  /__|
30//         \/     \/     \/  /_____/      \/      \/     \/     \/
31
32// This file contains common functions relating to setting the Repository for the
33// internal routes
34
35// RepoAssignment assigns the repository and gitrepository to the private context
36func RepoAssignment(ctx *gitea_context.PrivateContext) context.CancelFunc {
37	ownerName := ctx.Params(":owner")
38	repoName := ctx.Params(":repo")
39
40	repo := loadRepository(ctx, ownerName, repoName)
41	if ctx.Written() {
42		// Error handled in loadRepository
43		return nil
44	}
45
46	gitRepo, err := git.OpenRepository(repo.RepoPath())
47	if err != nil {
48		log.Error("Failed to open repository: %s/%s Error: %v", ownerName, repoName, err)
49		ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
50			"Err": fmt.Sprintf("Failed to open repository: %s/%s Error: %v", ownerName, repoName, err),
51		})
52		return nil
53	}
54
55	ctx.Repo = &gitea_context.Repository{
56		Repository: repo,
57		GitRepo:    gitRepo,
58	}
59
60	// We opened it, we should close it
61	cancel := func() {
62		// If it's been set to nil then assume someone else has closed it.
63		if ctx.Repo.GitRepo != nil {
64			ctx.Repo.GitRepo.Close()
65		}
66	}
67
68	return cancel
69}
70
71func loadRepository(ctx *gitea_context.PrivateContext, ownerName, repoName string) *repo_model.Repository {
72	repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName)
73	if err != nil {
74		log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
75		ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
76			"Err": fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
77		})
78		return nil
79	}
80	if repo.OwnerName == "" {
81		repo.OwnerName = ownerName
82	}
83	return repo
84}
85