Template Repositories (#8768)

* Start work on templates

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Continue work

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Fix IsTemplate vs IsGenerated

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Fix tabs vs spaces

* Tabs vs Spaces

* Add templates to API & start adding tests

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Fix integration tests

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Remove unused User

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Move template tests to existing repos

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Minor re-check updates and cleanup

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* make fmt

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Test cleanup

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Fix optionalbool

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* make fmt

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Test fixes and icon change

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Add new user and repo for tests

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Fix tests (finally)

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Update meta repo with env variables

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Move generation to create page

Combine with repo create template
Modify API search to prioritize owner for repo

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Fix tests and coverage

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Fix swagger and JS lint

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Fix API searching for own private repos

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Change wording

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Fix repo search test. User had a private repo that didn't show up

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Another search test fix

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Clarify git content

Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com>

* Feedback updates

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Add topics WIP

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Finish adding topics

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Update locale

Signed-off-by: jolheiser <john.olheiser@gmail.com>
tokarchuk/v1.17
John Olheiser 5 years ago committed by Lunny Xiao
parent 74bb292fe3
commit 74a6add4d9
  1. 10
      integrations/api_repo_test.go
  2. 1
      integrations/gitea-repositories-meta/user27/template1.git/HEAD
  3. 6
      integrations/gitea-repositories-meta/user27/template1.git/config
  4. 1
      integrations/gitea-repositories-meta/user27/template1.git/description
  5. 15
      integrations/gitea-repositories-meta/user27/template1.git/hooks/applypatch-msg.sample
  6. 24
      integrations/gitea-repositories-meta/user27/template1.git/hooks/commit-msg.sample
  7. 114
      integrations/gitea-repositories-meta/user27/template1.git/hooks/fsmonitor-watchman.sample
  8. 15
      integrations/gitea-repositories-meta/user27/template1.git/hooks/post-receive
  9. 2
      integrations/gitea-repositories-meta/user27/template1.git/hooks/post-receive.d/gitea
  10. 8
      integrations/gitea-repositories-meta/user27/template1.git/hooks/post-update.sample
  11. 14
      integrations/gitea-repositories-meta/user27/template1.git/hooks/pre-applypatch.sample
  12. 49
      integrations/gitea-repositories-meta/user27/template1.git/hooks/pre-commit.sample
  13. 53
      integrations/gitea-repositories-meta/user27/template1.git/hooks/pre-push.sample
  14. 169
      integrations/gitea-repositories-meta/user27/template1.git/hooks/pre-rebase.sample
  15. 15
      integrations/gitea-repositories-meta/user27/template1.git/hooks/pre-receive
  16. 2
      integrations/gitea-repositories-meta/user27/template1.git/hooks/pre-receive.d/gitea
  17. 24
      integrations/gitea-repositories-meta/user27/template1.git/hooks/pre-receive.sample
  18. 42
      integrations/gitea-repositories-meta/user27/template1.git/hooks/prepare-commit-msg.sample
  19. 14
      integrations/gitea-repositories-meta/user27/template1.git/hooks/update
  20. 2
      integrations/gitea-repositories-meta/user27/template1.git/hooks/update.d/gitea
  21. 128
      integrations/gitea-repositories-meta/user27/template1.git/hooks/update.sample
  22. 6
      integrations/gitea-repositories-meta/user27/template1.git/info/exclude
  23. 1
      integrations/gitea-repositories-meta/user27/template1.git/info/refs
  24. BIN
      integrations/gitea-repositories-meta/user27/template1.git/objects/47/34b1f84a367fa1b81c31aa4234a5bad11cafa3
  25. BIN
      integrations/gitea-repositories-meta/user27/template1.git/objects/4d/31f3a12656368a8d9180f431d40d0fc408be2d
  26. BIN
      integrations/gitea-repositories-meta/user27/template1.git/objects/51/f84af231345367fd5d61ceb89efb3b6d757061
  27. BIN
      integrations/gitea-repositories-meta/user27/template1.git/objects/79/3aa682b06ae032641abf70c5dfeade28c07c52
  28. BIN
      integrations/gitea-repositories-meta/user27/template1.git/objects/aa/cbdfe9e1c4b47f60abe81849045fa4e96f1d75
  29. BIN
      integrations/gitea-repositories-meta/user27/template1.git/objects/dd/392e939ea4936b2459219c9c9a1f25547ccaeb
  30. BIN
      integrations/gitea-repositories-meta/user27/template1.git/objects/f2/8eeca3df7614fd4f10c1030f13feb418ef3c6f
  31. 1
      integrations/gitea-repositories-meta/user27/template1.git/objects/info/packs
  32. 1
      integrations/gitea-repositories-meta/user27/template1.git/refs/heads/master
  33. 7
      integrations/integration_test.go
  34. 67
      integrations/repo_generate_test.go
  35. 14
      models/fixtures/repo_unit.yml
  36. 26
      models/fixtures/repository.yml
  37. 15
      models/fixtures/user.yml
  38. 2
      models/migrations/migrations.go
  39. 19
      models/migrations/v107.go
  40. 219
      models/repo.go
  41. 17
      models/repo_list.go
  42. 9
      models/repo_list_test.go
  43. 2
      models/user_test.go
  44. 5
      modules/auth/repo_form.go
  45. 27
      modules/context/repo.go
  46. 3
      modules/structs/repo.go
  47. 14
      options/locale/locale_en-US.ini
  48. 47
      public/js/index.js
  49. 19
      routers/api/v1/repo/repo.go
  50. 31
      routers/repo/pull.go
  51. 43
      routers/repo/repo.go
  52. 1
      routers/repo/setting.go
  53. 15
      services/repository/repository.go
  54. 29
      templates/repo/create.tmpl
  55. 2
      templates/repo/header.tmpl
  56. 11
      templates/repo/home.tmpl
  57. 7
      templates/repo/settings/options.tmpl
  58. 22
      templates/swagger/v1_json.tmpl

@ -70,9 +70,9 @@ func TestAPISearchRepo(t *testing.T) {
expectedResults
}{
{name: "RepositoriesMax50", requestURL: "/api/v1/repos/search?limit=50&private=false", expectedResults: expectedResults{
nil: {count: 22},
user: {count: 22},
user2: {count: 22}},
nil: {count: 24},
user: {count: 24},
user2: {count: 24}},
},
{name: "RepositoriesMax10", requestURL: "/api/v1/repos/search?limit=10&private=false", expectedResults: expectedResults{
nil: {count: 10},
@ -92,7 +92,7 @@ func TestAPISearchRepo(t *testing.T) {
{name: "RepositoriesAccessibleAndRelatedToUser", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user.ID), expectedResults: expectedResults{
nil: {count: 5},
user: {count: 9, includesPrivate: true},
user2: {count: 5, includesPrivate: true}},
user2: {count: 6, includesPrivate: true}},
},
{name: "RepositoriesAccessibleAndRelatedToUser2", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user2.ID), expectedResults: expectedResults{
nil: {count: 1},
@ -103,7 +103,7 @@ func TestAPISearchRepo(t *testing.T) {
{name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{
nil: {count: 1},
user: {count: 4, includesPrivate: true},
user2: {count: 2, includesPrivate: true},
user2: {count: 3, includesPrivate: true},
user3: {count: 4, includesPrivate: true}},
},
{name: "RepositoriesOwnedByOrganization", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", orgUser.ID), expectedResults: expectedResults{

@ -0,0 +1,6 @@
[core]
repositoryformatversion = 0
filemode = false
bare = true
symlinks = false
ignorecase = true

@ -0,0 +1 @@
Unnamed repository; edit this file 'description' to name the repository.

@ -0,0 +1,15 @@
#!/bin/sh
#
# An example hook script to check the commit log message taken by
# applypatch from an e-mail message.
#
# The hook should exit with non-zero status after issuing an
# appropriate message if it wants to stop the commit. The hook is
# allowed to edit the commit message file.
#
# To enable this hook, rename this file to "applypatch-msg".
. git-sh-setup
commitmsg="$(git rev-parse --git-path hooks/commit-msg)"
test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"}
:

@ -0,0 +1,24 @@
#!/bin/sh
#
# An example hook script to check the commit log message.
# Called by "git commit" with one argument, the name of the file
# that has the commit message. The hook should exit with non-zero
# status after issuing an appropriate message if it wants to stop the
# commit. The hook is allowed to edit the commit message file.
#
# To enable this hook, rename this file to "commit-msg".
# Uncomment the below to add a Signed-off-by line to the message.
# Doing this in a hook is a bad idea in general, but the prepare-commit-msg
# hook is more suited to it.
#
# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"
# This example catches duplicate Signed-off-by lines.
test "" = "$(grep '^Signed-off-by: ' "$1" |
sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || {
echo >&2 Duplicate Signed-off-by lines.
exit 1
}

@ -0,0 +1,114 @@
#!/usr/bin/perl
use strict;
use warnings;
use IPC::Open2;
# An example hook script to integrate Watchman
# (https://facebook.github.io/watchman/) with git to speed up detecting
# new and modified files.
#
# The hook is passed a version (currently 1) and a time in nanoseconds
# formatted as a string and outputs to stdout all files that have been
# modified since the given time. Paths must be relative to the root of
# the working tree and separated by a single NUL.
#
# To enable this hook, rename this file to "query-watchman" and set
# 'git config core.fsmonitor .git/hooks/query-watchman'
#
my ($version, $time) = @ARGV;
# Check the hook interface version
if ($version == 1) {
# convert nanoseconds to seconds
$time = int $time / 1000000000;
} else {
die "Unsupported query-fsmonitor hook version '$version'.\n" .
"Falling back to scanning...\n";
}
my $git_work_tree;
if ($^O =~ 'msys' || $^O =~ 'cygwin') {
$git_work_tree = Win32::GetCwd();
$git_work_tree =~ tr/\\/\//;
} else {
require Cwd;
$git_work_tree = Cwd::cwd();
}
my $retry = 1;
launch_watchman();
sub launch_watchman {
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty')
or die "open2() failed: $!\n" .
"Falling back to scanning...\n";
# In the query expression below we're asking for names of files that
# changed since $time but were not transient (ie created after
# $time but no longer exist).
#
# To accomplish this, we're using the "since" generator to use the
# recency index to select candidate nodes and "fields" to limit the
# output to file names only. Then we're using the "expression" term to
# further constrain the results.
#
# The category of transient files that we want to ignore will have a
# creation clock (cclock) newer than $time_t value and will also not
# currently exist.
my $query = <<" END";
["query", "$git_work_tree", {
"since": $time,
"fields": ["name"],
"expression": ["not", ["allof", ["since", $time, "cclock"], ["not", "exists"]]]
}]
END
print CHLD_IN $query;
close CHLD_IN;
my $response = do {local $/; <CHLD_OUT>};
die "Watchman: command returned no output.\n" .
"Falling back to scanning...\n" if $response eq "";
die "Watchman: command returned invalid output: $response\n" .
"Falling back to scanning...\n" unless $response =~ /^\{/;
my $json_pkg;
eval {
require JSON::XS;
$json_pkg = "JSON::XS";
1;
} or do {
require JSON::PP;
$json_pkg = "JSON::PP";
};
my $o = $json_pkg->new->utf8->decode($response);
if ($retry > 0 and $o->{error} and $o->{error} =~ m/unable to resolve root .* directory (.*) is not watched/) {
print STDERR "Adding '$git_work_tree' to watchman's watch list.\n";
$retry--;
qx/watchman watch "$git_work_tree"/;
die "Failed to make watchman watch '$git_work_tree'.\n" .
"Falling back to scanning...\n" if $? != 0;
# Watchman will always return all files on the first query so
# return the fast "everything is dirty" flag to git and do the
# Watchman query just to get it over with now so we won't pay
# the cost in git to look up each individual file.
print "/\0";
eval { launch_watchman() };
exit 0;
}
die "Watchman: $o->{error}.\n" .
"Falling back to scanning...\n" if $o->{error};
binmode STDOUT, ":utf8";
local $, = "\0";
print @{$o->{files}};
}

@ -0,0 +1,15 @@
#!/usr/bin/env bash
data=$(cat)
exitcodes=""
hookname=$(basename $0)
GIT_DIR=${GIT_DIR:-$(dirname $0)}
for hook in ${GIT_DIR}/hooks/${hookname}.d/*; do
test -x "${hook}" || continue
echo "${data}" | "${hook}"
exitcodes="${exitcodes} $?"
done
for i in ${exitcodes}; do
[ ${i} -eq 0 ] || exit ${i}
done

@ -0,0 +1,2 @@
#!/usr/bin/env bash
"$GITEA_ROOT/gitea" hook --config="$GITEA_ROOT/$GITEA_CONF" post-receive

@ -0,0 +1,8 @@
#!/bin/sh
#
# An example hook script to prepare a packed repository for use over
# dumb transports.
#
# To enable this hook, rename this file to "post-update".
exec git update-server-info

@ -0,0 +1,14 @@
#!/bin/sh
#
# An example hook script to verify what is about to be committed
# by applypatch from an e-mail message.
#
# The hook should exit with non-zero status after issuing an
# appropriate message if it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-applypatch".
. git-sh-setup
precommit="$(git rev-parse --git-path hooks/pre-commit)"
test -x "$precommit" && exec "$precommit" ${1+"$@"}
:

@ -0,0 +1,49 @@
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=$(git hash-object -t tree /dev/null)
fi
# If you want to allow non-ASCII filenames set this variable to true.
allownonascii=$(git config --bool hooks.allownonascii)
# Redirect output to stderr.
exec 1>&2
# Cross platform projects tend to avoid non-ASCII filenames; prevent
# them from being added to the repository. We exploit the fact that the
# printable range starts at the space character and ends with tilde.
if [ "$allownonascii" != "true" ] &&
# Note that the use of brackets around a tr range is ok here, (it's
# even required, for portability to Solaris 10's /usr/bin/tr), since
# the square bracket bytes happen to fall in the designated range.
test $(git diff --cached --name-only --diff-filter=A -z $against |
LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
then
cat <<\EOF
Error: Attempt to add a non-ASCII file name.
This can cause problems if you want to work with people on other platforms.
To be portable it is advisable to rename the file.
If you know what you are doing you can disable this check using:
git config hooks.allownonascii true
EOF
exit 1
fi
# If there are whitespace errors, print the offending file names and fail.
exec git diff-index --check --cached $against --

@ -0,0 +1,53 @@
#!/bin/sh
# An example hook script to verify what is about to be pushed. Called by "git
# push" after it has checked the remote status, but before anything has been
# pushed. If this script exits with a non-zero status nothing will be pushed.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
# <local ref> <local sha1> <remote ref> <remote sha1>
#
# This sample shows how to prevent push of commits where the log message starts
# with "WIP" (work in progress).
remote="$1"
url="$2"
z40=0000000000000000000000000000000000000000
while read local_ref local_sha remote_ref remote_sha
do
if [ "$local_sha" = $z40 ]
then
# Handle delete
:
else
if [ "$remote_sha" = $z40 ]
then
# New branch, examine all commits
range="$local_sha"
else
# Update to existing branch, examine new commits
range="$remote_sha..$local_sha"
fi
# Check for WIP commit
commit=`git rev-list -n 1 --grep '^WIP' "$range"`
if [ -n "$commit" ]
then
echo >&2 "Found WIP commit in $local_ref, not pushing"
exit 1
fi
fi
done
exit 0

@ -0,0 +1,169 @@
#!/bin/sh
#
# Copyright (c) 2006, 2008 Junio C Hamano
#
# The "pre-rebase" hook is run just before "git rebase" starts doing
# its job, and can prevent the command from running by exiting with
# non-zero status.
#
# The hook is called with the following parameters:
#
# $1 -- the upstream the series was forked from.
# $2 -- the branch being rebased (or empty when rebasing the current branch).
#
# This sample shows how to prevent topic branches that are already
# merged to 'next' branch from getting rebased, because allowing it
# would result in rebasing already published history.
publish=next
basebranch="$1"
if test "$#" = 2
then
topic="refs/heads/$2"
else
topic=`git symbolic-ref HEAD` ||
exit 0 ;# we do not interrupt rebasing detached HEAD
fi
case "$topic" in
refs/heads/??/*)
;;
*)
exit 0 ;# we do not interrupt others.
;;
esac
# Now we are dealing with a topic branch being rebased
# on top of master. Is it OK to rebase it?
# Does the topic really exist?
git show-ref -q "$topic" || {
echo >&2 "No such branch $topic"
exit 1
}
# Is topic fully merged to master?
not_in_master=`git rev-list --pretty=oneline ^master "$topic"`
if test -z "$not_in_master"
then
echo >&2 "$topic is fully merged to master; better remove it."
exit 1 ;# we could allow it, but there is no point.
fi
# Is topic ever merged to next? If so you should not be rebasing it.
only_next_1=`git rev-list ^master "^$topic" ${publish} | sort`
only_next_2=`git rev-list ^master ${publish} | sort`
if test "$only_next_1" = "$only_next_2"
then
not_in_topic=`git rev-list "^$topic" master`
if test -z "$not_in_topic"
then
echo >&2 "$topic is already up to date with master"
exit 1 ;# we could allow it, but there is no point.
else
exit 0
fi
else
not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"`
/usr/bin/perl -e '
my $topic = $ARGV[0];
my $msg = "* $topic has commits already merged to public branch:\n";
my (%not_in_next) = map {
/^([0-9a-f]+) /;
($1 => 1);
} split(/\n/, $ARGV[1]);
for my $elem (map {
/^([0-9a-f]+) (.*)$/;
[$1 => $2];
} split(/\n/, $ARGV[2])) {
if (!exists $not_in_next{$elem->[0]}) {
if ($msg) {
print STDERR $msg;
undef $msg;
}
print STDERR " $elem->[1]\n";
}
}
' "$topic" "$not_in_next" "$not_in_master"
exit 1
fi
<<\DOC_END
This sample hook safeguards topic branches that have been
published from being rewound.
The workflow assumed here is:
* Once a topic branch forks from "master", "master" is never
merged into it again (either directly or indirectly).
* Once a topic branch is fully cooked and merged into "master",
it is deleted. If you need to build on top of it to correct
earlier mistakes, a new topic branch is created by forking at
the tip of the "master". This is not strictly necessary, but
it makes it easier to keep your history simple.
* Whenever you need to test or publish your changes to topic
branches, merge them into "next" branch.
The script, being an example, hardcodes the publish branch name
to be "next", but it is trivial to make it configurable via
$GIT_DIR/config mechanism.
With this workflow, you would want to know:
(1) ... if a topic branch has ever been merged to "next". Young
topic branches can have stupid mistakes you would rather
clean up before publishing, and things that have not been
merged into other branches can be easily rebased without
affecting other people. But once it is published, you would
not want to rewind it.
(2) ... if a topic branch has been fully merged to "master".
Then you can delete it. More importantly, you should not
build on top of it -- other people may already want to
change things related to the topic as patches against your
"master", so if you need further changes, it is better to
fork the topic (perhaps with the same name) afresh from the
tip of "master".
Let's look at this example:
o---o---o---o---o---o---o---o---o---o "next"
/ / / /
/ a---a---b A / /
/ / / /
/ / c---c---c---c B /
/ / / \ /
/ / / b---b C \ /
/ / / / \ /
---o---o---o---o---o---o---o---o---o---o---o "master"
A, B and C are topic branches.
* A has one fix since it was merged up to "next".
* B has finished. It has been fully merged up to "master" and "next",
and is ready to be deleted.
* C has not merged to "next" at all.
We would want to allow C to be rebased, refuse A, and encourage
B to be deleted.
To compute (1):
git rev-list ^master ^topic next
git rev-list ^master next
if these match, topic has not merged in next at all.
To compute (2):
git rev-list master..topic
if this is empty, it is fully merged to "master".
DOC_END

@ -0,0 +1,15 @@
#!/usr/bin/env bash
data=$(cat)
exitcodes=""
hookname=$(basename $0)
GIT_DIR=${GIT_DIR:-$(dirname $0)}
for hook in ${GIT_DIR}/hooks/${hookname}.d/*; do
test -x "${hook}" || continue
echo "${data}" | "${hook}"
exitcodes="${exitcodes} $?"
done
for i in ${exitcodes}; do
[ ${i} -eq 0 ] || exit ${i}
done

@ -0,0 +1,2 @@
#!/usr/bin/env bash
"$GITEA_ROOT/gitea" hook --config="$GITEA_ROOT/$GITEA_CONF" pre-receive

@ -0,0 +1,24 @@
#!/bin/sh
#
# An example hook script to make use of push options.
# The example simply echoes all push options that start with 'echoback='
# and rejects all pushes when the "reject" push option is used.
#
# To enable this hook, rename this file to "pre-receive".
if test -n "$GIT_PUSH_OPTION_COUNT"
then
i=0
while test "$i" -lt "$GIT_PUSH_OPTION_COUNT"
do
eval "value=\$GIT_PUSH_OPTION_$i"
case "$value" in
echoback=*)
echo "echo from the pre-receive-hook: ${value#*=}" >&2
;;
reject)
exit 1
esac
i=$((i + 1))
done
fi

@ -0,0 +1,42 @@
#!/bin/sh
#
# An example hook script to prepare the commit log message.
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source. The hook's purpose is to edit the commit
# message file. If the hook fails with a non-zero status,
# the commit is aborted.
#
# To enable this hook, rename this file to "prepare-commit-msg".
# This hook includes three examples. The first one removes the
# "# Please enter the commit message..." help message.
#
# The second includes the output of "git diff --name-status -r"
# into the message, just before the "git status" output. It is
# commented because it doesn't cope with --amend or with squashed
# commits.
#
# The third example adds a Signed-off-by line to the message, that can
# still be edited. This is rarely a good idea.
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE"
# case "$COMMIT_SOURCE,$SHA1" in
# ,|template,)
# /usr/bin/perl -i.bak -pe '
# print "\n" . `git diff --cached --name-status -r`
# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;;
# *) ;;
# esac
# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE"
# if test -z "$COMMIT_SOURCE"
# then
# /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE"
# fi

@ -0,0 +1,14 @@
#!/usr/bin/env bash
exitcodes=""
hookname=$(basename $0)
GIT_DIR=${GIT_DIR:-$(dirname $0)}
for hook in ${GIT_DIR}/hooks/${hookname}.d/*; do
test -x "${hook}" || continue
"${hook}" $1 $2 $3
exitcodes="${exitcodes} $?"
done
for i in ${exitcodes}; do
[ ${i} -eq 0 ] || exit ${i}
done

@ -0,0 +1,2 @@
#!/usr/bin/env bash
"$GITEA_ROOT/gitea" hook --config="$GITEA_ROOT/$GITEA_CONF" update $1 $2 $3

@ -0,0 +1,128 @@
#!/bin/sh
#
# An example hook script to block unannotated tags from entering.
# Called by "git receive-pack" with arguments: refname sha1-old sha1-new
#
# To enable this hook, rename this file to "update".
#
# Config
# ------
# hooks.allowunannotated
# This boolean sets whether unannotated tags will be allowed into the
# repository. By default they won't be.
# hooks.allowdeletetag
# This boolean sets whether deleting tags will be allowed in the
# repository. By default they won't be.
# hooks.allowmodifytag
# This boolean sets whether a tag may be modified after creation. By default
# it won't be.
# hooks.allowdeletebranch
# This boolean sets whether deleting branches will be allowed in the
# repository. By default they won't be.
# hooks.denycreatebranch
# This boolean sets whether remotely creating branches will be denied
# in the repository. By default this is allowed.
#
# --- Command line
refname="$1"
oldrev="$2"
newrev="$3"
# --- Safety check
if [ -z "$GIT_DIR" ]; then
echo "Don't run this script from the command line." >&2
echo " (if you want, you could supply GIT_DIR then run" >&2
echo " $0 <ref> <oldrev> <newrev>)" >&2
exit 1
fi
if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then
echo "usage: $0 <ref> <oldrev> <newrev>" >&2
exit 1
fi
# --- Config
allowunannotated=$(git config --bool hooks.allowunannotated)
allowdeletebranch=$(git config --bool hooks.allowdeletebranch)
denycreatebranch=$(git config --bool hooks.denycreatebranch)
allowdeletetag=$(git config --bool hooks.allowdeletetag)
allowmodifytag=$(git config --bool hooks.allowmodifytag)
# check for no description
projectdesc=$(sed -e '1q' "$GIT_DIR/description")
case "$projectdesc" in
"Unnamed repository"* | "")
echo "*** Project description file hasn't been set" >&2
exit 1
;;
esac
# --- Check types
# if $newrev is 0000...0000, it's a commit to delete a ref.
zero="0000000000000000000000000000000000000000"
if [ "$newrev" = "$zero" ]; then
newrev_type=delete
else
newrev_type=$(git cat-file -t $newrev)
fi
case "$refname","$newrev_type" in
refs/tags/*,commit)
# un-annotated tag
short_refname=${refname##refs/tags/}
if [ "$allowunannotated" != "true" ]; then
echo "*** The un-annotated tag, $short_refname, is not allowed in this repository" >&2
echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2
exit 1
fi
;;
refs/tags/*,delete)
# delete tag
if [ "$allowdeletetag" != "true" ]; then
echo "*** Deleting a tag is not allowed in this repository" >&2
exit 1
fi
;;
refs/tags/*,tag)
# annotated tag
if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1
then
echo "*** Tag '$refname' already exists." >&2
echo "*** Modifying a tag is not allowed in this repository." >&2
exit 1
fi
;;
refs/heads/*,commit)
# branch
if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then
echo "*** Creating a branch is not allowed in this repository" >&2
exit 1
fi
;;
refs/heads/*,delete)
# delete branch
if [ "$allowdeletebranch" != "true" ]; then
echo "*** Deleting a branch is not allowed in this repository" >&2
exit 1
fi
;;
refs/remotes/*,commit)
# tracking branch
;;
refs/remotes/*,delete)
# delete tracking branch
if [ "$allowdeletebranch" != "true" ]; then
echo "*** Deleting a tracking branch is not allowed in this repository" >&2
exit 1
fi
;;
*)
# Anything else (is there anything else?)
echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2
exit 1
;;
esac
# --- Finished
exit 0

@ -0,0 +1,6 @@
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~

@ -0,0 +1 @@
aacbdfe9e1c4b47f60abe81849045fa4e96f1d75 refs/heads/master

@ -18,6 +18,7 @@ import (
"os"
"path"
"path/filepath"
"runtime"
"strings"
"testing"
@ -102,7 +103,11 @@ func initIntegrationTest() {
fmt.Println("Environment variable $GITEA_ROOT not set")
os.Exit(1)
}
setting.AppPath = path.Join(giteaRoot, "gitea")
giteaBinary := "gitea"
if runtime.GOOS == "windows" {
giteaBinary += ".exe"
}
setting.AppPath = path.Join(giteaRoot, giteaBinary)
if _, err := os.Stat(setting.AppPath); err != nil {
fmt.Printf("Could not find gitea binary at %s\n", setting.AppPath)
os.Exit(1)

@ -0,0 +1,67 @@
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package integrations
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"code.gitea.io/gitea/models"
"github.com/stretchr/testify/assert"
)
func testRepoGenerate(t *testing.T, session *TestSession, templateOwnerName, templateRepoName, generateOwnerName, generateRepoName string) *httptest.ResponseRecorder {
generateOwner := models.AssertExistsAndLoadBean(t, &models.User{Name: generateOwnerName}).(*models.User)
// Step0: check the existence of the generated repo
req := NewRequestf(t, "GET", "/%s/%s", generateOwnerName, generateRepoName)
resp := session.MakeRequest(t, req, http.StatusNotFound)
// Step1: go to the main page of template repo
req = NewRequestf(t, "GET", "/%s/%s", templateOwnerName, templateRepoName)
resp = session.MakeRequest(t, req, http.StatusOK)
// Step2: click the "Use this template" button
htmlDoc := NewHTMLParser(t, resp.Body)
link, exists := htmlDoc.doc.Find("a.ui.button[href^=\"/repo/create\"]").Attr("href")
assert.True(t, exists, "The template has changed")
req = NewRequest(t, "GET", link)
resp = session.MakeRequest(t, req, http.StatusOK)
// Step3: fill the form of the create
htmlDoc = NewHTMLParser(t, resp.Body)
link, exists = htmlDoc.doc.Find("form.ui.form[action^=\"/repo/create\"]").Attr("action")
assert.True(t, exists, "The template has changed")
_, exists = htmlDoc.doc.Find(fmt.Sprintf(".owner.dropdown .item[data-value=\"%d\"]", generateOwner.ID)).Attr("data-value")
assert.True(t, exists, fmt.Sprintf("Generate owner '%s' is not present in select box", generateOwnerName))
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"uid": fmt.Sprintf("%d", generateOwner.ID),
"repo_name": generateRepoName,
"git_content": "true",
})
resp = session.MakeRequest(t, req, http.StatusFound)
// Step4: check the existence of the generated repo
req = NewRequestf(t, "GET", "/%s/%s", generateOwnerName, generateRepoName)
resp = session.MakeRequest(t, req, http.StatusOK)
return resp
}
func TestRepoGenerate(t *testing.T) {
prepareTestEnv(t)
session := loginUser(t, "user1")
testRepoGenerate(t, session, "user27", "template1", "user1", "generated1")
}
func TestRepoGenerateToOrg(t *testing.T) {
prepareTestEnv(t)
session := loginUser(t, "user2")
testRepoGenerate(t, session, "user27", "template1", "user2", "generated2")
}

@ -438,3 +438,17 @@
type: 3
config: "{\"IgnoreWhitespaceConflicts\":false,\"AllowMerge\":true,\"AllowRebase\":true,\"AllowRebaseMerge\":true,\"AllowSquash\":true}"
created_unix: 946684810
-
id: 64
repo_id: 44
type: 1
config: "{}"
created_unix: 946684810
-
id: 65
repo_id: 45
type: 1
config: "{}"
created_unix: 946684810

@ -561,3 +561,29 @@
num_issues: 0
is_mirror: false
status: 0
-
id: 44
owner_id: 27
lower_name: template1
name: template1
is_private: false
is_template: true
num_stars: 0
num_forks: 0
num_issues: 0
is_mirror: false
status: 0
-
id: 45
owner_id: 27
lower_name: template2
name: template2
is_private: false
is_template: true
num_stars: 0
num_forks: 0
num_issues: 0
is_mirror: false
status: 0

@ -428,3 +428,18 @@
num_members: 0
num_teams: 1
repo_admin_change_team_access: true
-
id: 27
lower_name: user27
name: user27
full_name: User Twenty-Seven
email: user27@example.com
email_notifications_preference: enabled
passwd: 7d93daa0d1e6f2305cc8fa496847d61dc7320bb16262f9c55dd753480207234cdd96a93194e408341971742f4701772a025a # password
type: 0 # individual
salt: ZogKvWdyEx
is_admin: false
avatar: avatar27
avatar_email: user27@example.com
num_repos: 2

@ -268,6 +268,8 @@ var migrations = []Migration{
NewMigration("add includes_all_repositories to teams", addTeamIncludesAllRepositories),
// v106 -> v107
NewMigration("add column `mode` to table watch", addModeColumnToWatch),
// v107 -> v108
NewMigration("Add template options to repository", addTemplateToRepo),
}
// Migrate database to current version

@ -0,0 +1,19 @@
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package migrations
import (
"xorm.io/xorm"
)
func addTemplateToRepo(x *xorm.Engine) error {
type Repository struct {
IsTemplate bool `xorm:"INDEX NOT NULL DEFAULT false"`
TemplateID int64 `xorm:"INDEX"`
}
return x.Sync2(new(Repository))
}

@ -179,6 +179,9 @@ type Repository struct {
IsFork bool `xorm:"INDEX NOT NULL DEFAULT false"`
ForkID int64 `xorm:"INDEX"`
BaseRepo *Repository `xorm:"-"`
IsTemplate bool `xorm:"INDEX NOT NULL DEFAULT false"`
TemplateID int64 `xorm:"INDEX"`
TemplateRepo *Repository `xorm:"-"`
Size int64 `xorm:"NOT NULL DEFAULT 0"`
IndexerStatus *RepoIndexerStatus `xorm:"-"`
IsFsckEnabled bool `xorm:"NOT NULL DEFAULT true"`
@ -351,6 +354,7 @@ func (repo *Repository) innerAPIFormat(e Engine, mode AccessMode, isParent bool)
FullName: repo.FullName(),
Description: repo.Description,
Private: repo.IsPrivate,
Template: repo.IsTemplate,
Empty: repo.IsEmpty,
Archived: repo.IsArchived,
Size: int(repo.Size / 1024),
@ -663,6 +667,27 @@ func (repo *Repository) getBaseRepo(e Engine) (err error) {
return err
}
// IsGenerated returns whether _this_ repository was generated from a template
func (repo *Repository) IsGenerated() bool {
return repo.TemplateID != 0
}
// GetTemplateRepo populates repo.TemplateRepo for a generated repository and
// returns an error on failure (NOTE: no error is returned for
// non-generated repositories, and TemplateRepo will be left untouched)
func (repo *Repository) GetTemplateRepo() (err error) {
return repo.getTemplateRepo(x)
}
func (repo *Repository) getTemplateRepo(e Engine) (err error) {
if !repo.IsGenerated() {
return nil
}
repo.TemplateRepo, err = getRepositoryByID(e, repo.TemplateID)
return err
}
func (repo *Repository) repoPath(e Engine) string {
return RepoPath(repo.mustOwnerName(e), repo.Name)
}
@ -1220,6 +1245,20 @@ type CreateRepoOptions struct {
Status RepositoryStatus
}
// GenerateRepoOptions contains the template units to generate
type GenerateRepoOptions struct {
Name string
Description string
Private bool
GitContent bool
Topics bool
}
// IsValid checks whether at least one option is chosen for generation
func (gro GenerateRepoOptions) IsValid() bool {
return gro.GitContent || gro.Topics // or other items as they are added
}
func getRepoInitFile(tp, name string) ([]byte, error) {
cleanedName := strings.TrimLeft(path.Clean("/"+name), "/")
relPath := path.Join("options", tp, cleanedName)
@ -1323,8 +1362,55 @@ func prepareRepoCommit(e Engine, repo *Repository, tmpDir, repoPath string, opts
return nil
}
// InitRepository initializes README and .gitignore if needed.
func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) (err error) {
func generateRepoCommit(e Engine, repo, templateRepo *Repository, tmpDir string) error {
commitTimeStr := time.Now().Format(time.RFC3339)
authorSig := repo.Owner.NewGitSig()
// Because this may call hooks we should pass in the environment
env := append(os.Environ(),
"GIT_AUTHOR_NAME="+authorSig.Name,
"GIT_AUTHOR_EMAIL="+authorSig.Email,
"GIT_AUTHOR_DATE="+commitTimeStr,
"GIT_COMMITTER_NAME="+authorSig.Name,
"GIT_COMMITTER_EMAIL="+authorSig.Email,
"GIT_COMMITTER_DATE="+commitTimeStr,
)
// Clone to temporary path and do the init commit.
templateRepoPath := templateRepo.repoPath(e)
_, stderr, err := process.GetManager().ExecDirEnv(
-1, "",
fmt.Sprintf("generateRepoCommit(git clone): %s", templateRepoPath),
env,
git.GitExecutable, "clone", "--depth", "1", templateRepoPath, tmpDir,
)
if err != nil {
return fmt.Errorf("git clone: %v - %s", err, stderr)
}
if err := os.RemoveAll(path.Join(tmpDir, ".git")); err != nil {
return fmt.Errorf("remove git dir: %v", err)
}
if err := git.InitRepository(tmpDir, false); err != nil {
return err
}
repoPath := repo.repoPath(e)
_, stderr, err = process.GetManager().ExecDirEnv(
-1, tmpDir,
fmt.Sprintf("generateRepoCommit(git remote add): %s", repoPath),
env,
git.GitExecutable, "remote", "add", "origin", repoPath,
)
if err != nil {
return fmt.Errorf("git remote add: %v - %s", err, stderr)
}
return initRepoCommit(tmpDir, repo.Owner)
}
func checkInitRepository(repoPath string) (err error) {
// Somehow the directory could exist.
if com.IsExist(repoPath) {
return fmt.Errorf("initRepository: path already exists: %s", repoPath)
@ -1336,6 +1422,14 @@ func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts C
} else if err = createDelegateHooks(repoPath); err != nil {
return fmt.Errorf("createDelegateHooks: %v", err)
}
return nil
}
// InitRepository initializes README and .gitignore if needed.
func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) (err error) {
if err = checkInitRepository(repoPath); err != nil {
return err
}
tmpDir := filepath.Join(os.TempDir(), "gitea-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
@ -1376,6 +1470,37 @@ func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts C
return nil
}
// generateRepository initializes repository from template
func generateRepository(e Engine, repo, templateRepo *Repository) (err error) {
tmpDir := filepath.Join(os.TempDir(), "gitea-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil {
return fmt.Errorf("Failed to create dir %s: %v", tmpDir, err)
}
defer func() {
if err := os.RemoveAll(tmpDir); err != nil {
log.Error("RemoveAll: %v", err)
}
}()
if err = generateRepoCommit(e, repo, templateRepo, tmpDir); err != nil {
return fmt.Errorf("generateRepoCommit: %v", err)
}
// re-fetch repo
if repo, err = getRepositoryByID(e, repo.ID); err != nil {
return fmt.Errorf("getRepositoryByID: %v", err)
}
repo.DefaultBranch = "master"
if err = updateRepository(e, repo, false); err != nil {
return fmt.Errorf("updateRepository: %v", err)
}
return nil
}
var (
reservedRepoNames = []string{".", ".."}
reservedRepoPatterns = []string{"*.git", "*.wiki"}
@ -2523,6 +2648,28 @@ func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
return repo, has
}
// CopyLFS copies LFS data from one repo to another
func CopyLFS(newRepo, oldRepo *Repository) error {
return copyLFS(x, newRepo, oldRepo)
}
func copyLFS(e Engine, newRepo, oldRepo *Repository) error {
var lfsObjects []*LFSMetaObject
if err := e.Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
return err
}
for _, v := range lfsObjects {
v.ID = 0
v.RepositoryID = newRepo.ID
if _, err := e.Insert(v); err != nil {
return err
}
}
return nil
}
// ForkRepository forks a repository
func ForkRepository(doer, owner *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
forkedRepo, err := oldRepo.GetUserFork(owner.ID)
@ -2593,27 +2740,73 @@ func ForkRepository(doer, owner *User, oldRepo *Repository, name, desc string) (
log.Error("Failed to update size for repository: %v", err)
}
// Copy LFS meta objects in new session
sess2 := x.NewSession()
defer sess2.Close()
if err = sess2.Begin(); err != nil {
return repo, CopyLFS(repo, oldRepo)
}
// GenerateRepository generates a repository from a template
func GenerateRepository(doer, owner *User, templateRepo *Repository, opts GenerateRepoOptions) (_ *Repository, err error) {
repo := &Repository{
OwnerID: owner.ID,
Owner: owner,
Name: opts.Name,
LowerName: strings.ToLower(opts.Name),
Description: opts.Description,
IsPrivate: opts.Private,
IsEmpty: !opts.GitContent || templateRepo.IsEmpty,
IsFsckEnabled: templateRepo.IsFsckEnabled,
TemplateID: templateRepo.ID,
}
createSess := x.NewSession()
defer createSess.Close()
if err = createSess.Begin(); err != nil {
return nil, err
}
if err = createRepository(createSess, doer, owner, repo); err != nil {
return nil, err
}
//Commit repo to get created repo ID
err = createSess.Commit()
if err != nil {
return nil, err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return repo, err
}
var lfsObjects []*LFSMetaObject
if err = sess2.Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
repoPath := RepoPath(owner.Name, repo.Name)
if err = checkInitRepository(repoPath); err != nil {
return repo, err
}
for _, v := range lfsObjects {
v.ID = 0
v.RepositoryID = repo.ID
if _, err = sess2.Insert(v); err != nil {
if opts.GitContent && !templateRepo.IsEmpty {
if err = generateRepository(sess, repo, templateRepo); err != nil {
return repo, err
}
if err = repo.updateSize(sess); err != nil {
return repo, fmt.Errorf("failed to update size for repository: %v", err)
}
if err = copyLFS(sess, repo, templateRepo); err != nil {
return repo, fmt.Errorf("failed to copy LFS: %v", err)
}
}
if opts.Topics {
for _, topic := range templateRepo.Topics {
if _, err = addTopicByNameToRepo(sess, repo.ID, topic); err != nil {
return repo, err
}
}
}
return repo, sess2.Commit()
return repo, sess.Commit()
}
// GetForks returns all the forks of the repository

@ -115,6 +115,7 @@ type SearchRepoOptions struct {
UserIsAdmin bool
Keyword string
OwnerID int64
PriorityOwnerID int64
OrderBy SearchOrderBy
Private bool // Include private repositories in results
StarredByID int64
@ -130,6 +131,10 @@ type SearchRepoOptions struct {
// True -> include just forks
// False -> include just non-forks
Fork util.OptionalBool
// None -> include templates AND non-templates
// True -> include just templates
// False -> include just non-templates
Template util.OptionalBool
// None -> include mirrors AND non-mirrors
// True -> include just mirrors
// False -> include just non-mirrors
@ -190,6 +195,10 @@ func SearchRepository(opts *SearchRepoOptions) (RepositoryList, int64, error) {
cond = cond.And(accessCond)
}
if opts.Template != util.OptionalBoolNone {
cond = cond.And(builder.Eq{"is_template": opts.Template == util.OptionalBoolTrue})
}
// Restrict to starred repositories
if opts.StarredByID > 0 {
cond = cond.And(builder.In("id", builder.Select("repo_id").From("star").Where(builder.Eq{"uid": opts.StarredByID})))
@ -266,6 +275,10 @@ func SearchRepository(opts *SearchRepoOptions) (RepositoryList, int64, error) {
opts.OrderBy = SearchOrderByAlphabetically
}
if opts.PriorityOwnerID > 0 {
opts.OrderBy = SearchOrderBy(fmt.Sprintf("CASE WHEN owner_id = %d THEN 0 ELSE owner_id END, %s", opts.PriorityOwnerID, opts.OrderBy))
}
sess := x.NewSession()
defer sess.Close()
@ -308,11 +321,15 @@ func accessibleRepositoryCondition(userID int64) builder.Cond {
builder.NotIn("`repository`.owner_id", builder.Select("id").From("`user`").Where(builder.Eq{"visibility": structs.VisibleTypePrivate}))),
),
// 2. Be able to see all repositories that we have access to
builder.Or(
builder.In("`repository`.id", builder.Select("repo_id").
From("`access`").
Where(builder.And(
builder.Eq{"user_id": userID},
builder.Gt{"mode": int(AccessModeNone)}))),
builder.In("`repository`.id", builder.Select("id").
From("`repository`").
Where(builder.Eq{"owner_id": userID}))),
// 3. Be able to see all repositories that we are in a team
builder.In("`repository`.id", builder.Select("`team_repo`.repo_id").
From("team_repo").

@ -174,10 +174,10 @@ func TestSearchRepository(t *testing.T) {
opts: &SearchRepoOptions{Keyword: "big_test_", Page: 1, PageSize: 10, Private: true, AllPublic: true, Collaborate: util.OptionalBoolFalse},
count: 14},
{name: "AllPublic/PublicRepositoriesOfUserIncludingCollaborative",
opts: &SearchRepoOptions{Page: 1, PageSize: 10, OwnerID: 15, AllPublic: true},
opts: &SearchRepoOptions{Page: 1, PageSize: 10, OwnerID: 15, AllPublic: true, Template: util.OptionalBoolFalse},
count: 22},
{name: "AllPublic/PublicAndPrivateRepositoriesOfUserIncludingCollaborative",
opts: &SearchRepoOptions{Page: 1, PageSize: 10, OwnerID: 15, Private: true, AllPublic: true},
opts: &SearchRepoOptions{Page: 1, PageSize: 10, OwnerID: 15, Private: true, AllPublic: true, Template: util.OptionalBoolFalse},
count: 28},
{name: "AllPublic/PublicAndPrivateRepositoriesOfUserIncludingCollaborativeByName",
opts: &SearchRepoOptions{Keyword: "test", Page: 1, PageSize: 10, OwnerID: 15, Private: true, AllPublic: true},
@ -186,8 +186,11 @@ func TestSearchRepository(t *testing.T) {
opts: &SearchRepoOptions{Keyword: "test", Page: 1, PageSize: 10, OwnerID: 18, Private: true, AllPublic: true},
count: 13},
{name: "AllPublic/PublicRepositoriesOfOrganization",
opts: &SearchRepoOptions{Page: 1, PageSize: 10, OwnerID: 17, AllPublic: true, Collaborate: util.OptionalBoolFalse},
opts: &SearchRepoOptions{Page: 1, PageSize: 10, OwnerID: 17, AllPublic: true, Collaborate: util.OptionalBoolFalse, Template: util.OptionalBoolFalse},
count: 22},
{name: "AllTemplates",
opts: &SearchRepoOptions{Page: 1, PageSize: 10, Template: util.OptionalBoolTrue},
count: 2},
}
for _, testCase := range testCases {

@ -153,7 +153,7 @@ func TestSearchUsers(t *testing.T) {
}
testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 1},
[]int64{1, 2, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 24})
[]int64{1, 2, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 24, 27})
testUserSuccess(&SearchUserOptions{Page: 1, IsActive: util.OptionalBoolFalse},
[]int64{9})

@ -36,6 +36,10 @@ type CreateRepoForm struct {
IssueLabels string
License string
Readme string
RepoTemplate int64
GitContent bool
Topics bool
}
// Validate validates the fields
@ -107,6 +111,7 @@ type RepoSettingForm struct {
MirrorUsername string
MirrorPassword string
Private bool
Template bool
EnablePrune bool
// Advanced settings

@ -189,6 +189,26 @@ func RetrieveBaseRepo(ctx *Context, repo *models.Repository) {
}
}
// RetrieveTemplateRepo retrieves template repository used to generate this repository
func RetrieveTemplateRepo(ctx *Context, repo *models.Repository) {
// Non-generated repository will not return error in this method.
if err := repo.GetTemplateRepo(); err != nil {
if models.IsErrRepoNotExist(err) {
repo.TemplateID = 0
return
}
ctx.ServerError("GetTemplateRepo", err)
return
} else if err = repo.TemplateRepo.GetOwner(); err != nil {
ctx.ServerError("TemplateRepo.GetOwner", err)
return
}
if !repo.TemplateRepo.CheckUnitUser(ctx.User.ID, ctx.User.IsAdmin, models.UnitTypeCode) {
repo.TemplateID = 0
}
}
// ComposeGoGetImport returns go-get-import meta content.
func ComposeGoGetImport(owner, repo string) string {
/// setting.AppUrl is guaranteed to be parse as url
@ -414,6 +434,13 @@ func RepoAssignment() macaron.Handler {
}
}
if repo.IsGenerated() {
RetrieveTemplateRepo(ctx, repo)
if ctx.Written() {
return
}
}
// Disable everything when the repo is being created
if ctx.Repo.Repository.IsBeingCreated() {
ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch

@ -54,6 +54,7 @@ type Repository struct {
Empty bool `json:"empty"`
Private bool `json:"private"`
Fork bool `json:"fork"`
Template bool `json:"template"`
Parent *Repository `json:"parent"`
Mirror bool `json:"mirror"`
Size int `json:"size"`
@ -125,6 +126,8 @@ type EditRepoOption struct {
// Note: you will get a 422 error if the organization restricts changing repository visibility to organization
// owners and a non-owner tries to change the value of private.
Private *bool `json:"private,omitempty"`
// either `true` to make this repository a template or `false` to make it a normal repository
Template *bool `json:"template,omitempty"`
// either `true` to enable issues for this repository or `false` to disable them.
HasIssues *bool `json:"has_issues,omitempty"`
// set this structure to configure internal issue tracker (requires has_issues)

@ -582,6 +582,10 @@ email_notifications.submit = Set Email Preference
owner = Owner
repo_name = Repository Name
repo_name_helper = Good repository names use short, memorable and unique keywords.
template = Template
template_select = Select a template.
template_helper = Make repository a template
template_description = Template repositories let users generate new repositories with the same directory structure, files, and optional settings.
visibility = Visibility
visibility_description = Only the owner or the organization members if they have rights, will be able to see it.
visibility_helper = Make Repository Private
@ -591,6 +595,9 @@ clone_helper = Need help cloning? Visit <a target="_blank" rel="noopener norefer
fork_repo = Fork Repository
fork_from = Fork From
fork_visibility_helper = The visibility of a forked repository cannot be changed.
use_template = Use this template
generate_repo = Generate Repository
generate_from = Generate From
repo_desc = Description
repo_lang = Language
repo_gitignore_helper = Select .gitignore templates.
@ -618,6 +625,12 @@ forks = Forks
pick_reaction = Pick your reaction
reactions_more = and %d more
template.items = Template Items
template.git_content = Git Content (Default Branch)
template.topics = Topics
template.one_item = Must select at least one template item
template.invalid = Must select a template repository
archive.title = This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
archive.issue.nocomment = This repo is archived. You cannot comment on issues.
archive.pull.nocomment = This repo is archived. You cannot comment on pull requests.
@ -652,6 +665,7 @@ migrate.migrating_failed = Migrating from <b>%s</b> failed.
mirror_from = mirror of
forked_from = forked from
generated_from = generated from
fork_from_self = You cannot fork a repository you own.
fork_guest_user = Sign in to fork this repository.
copy_link = Copy

@ -2135,6 +2135,52 @@ function initWipTitle() {
});
}
function initTemplateSearch() {
const $repoTemplate = $("#repo_template");
const checkTemplate = function() {
const $templateUnits = $("#template_units");
const $nonTemplate = $("#non_template");
if ($repoTemplate.val() !== "") {
$templateUnits.show();
$nonTemplate.hide();
} else {
$templateUnits.hide();
$nonTemplate.show();
}
};
$repoTemplate.change(checkTemplate);
checkTemplate();
const changeOwner = function() {
$("#repo_template_search")
.dropdown({
apiSettings: {
url: suburl + '/api/v1/repos/search?q={query}&template=true&priority_owner_id=' + $("#uid").val(),
onResponse: function(response) {
const filteredResponse = {'success': true, 'results': []};
filteredResponse.results.push({
'name': '',
'value': ''
});
// Parse the response from the api to work with our dropdown
$.each(response.data, function(_r, repo) {
filteredResponse.results.push({
'name' : htmlEncode(repo.full_name) ,
'value' : repo.id
});
});
return filteredResponse;
},
cache: false,
},
fullTextSearch: true
});
};
$("#uid").change(changeOwner);
changeOwner();
}
$(document).ready(function () {
csrf = $('meta[name=_csrf]').attr("content");
suburl = $('meta[name=_suburl]').attr("content");
@ -2377,6 +2423,7 @@ $(document).ready(function () {
initWipTitle();
initPullRequestReview();
initRepoStatusChecker();
initTemplateSearch();
// Repo clone url.
if ($('#repo-clone-url').length > 0) {

@ -71,6 +71,11 @@ func Search(ctx *context.APIContext) {
// description: search only for repos that the user with the given id owns or contributes to
// type: integer
// format: int64
// - name: priority_owner_id
// in: query
// description: repo owner to prioritize in the results
// type: integer
// format: int64
// - name: starredBy
// in: query
// description: search only for repos that the user with the given id has starred
@ -80,6 +85,10 @@ func Search(ctx *context.APIContext) {
// in: query
// description: include private repositories this user has access to (defaults to true)
// type: boolean
// - name: template
// in: query
// description: include template repositories this user has access to (defaults to true)
// type: boolean
// - name: page
// in: query
// description: page number of results to return (1-based)
@ -116,17 +125,23 @@ func Search(ctx *context.APIContext) {
opts := &models.SearchRepoOptions{
Keyword: strings.Trim(ctx.Query("q"), " "),
OwnerID: ctx.QueryInt64("uid"),
PriorityOwnerID: ctx.QueryInt64("priority_owner_id"),
Page: ctx.QueryInt("page"),
PageSize: convert.ToCorrectPageSize(ctx.QueryInt("limit")),
TopicOnly: ctx.QueryBool("topic"),
Collaborate: util.OptionalBoolNone,
Private: ctx.IsSigned && (ctx.Query("private") == "" || ctx.QueryBool("private")),
Template: util.OptionalBoolNone,
UserIsAdmin: ctx.IsUserSiteAdmin(),
UserID: ctx.Data["SignedUserID"].(int64),
StarredByID: ctx.QueryInt64("starredBy"),
IncludeDescription: ctx.QueryBool("includeDesc"),
}
if ctx.Query("template") != "" {
opts.Template = util.OptionalBoolOf(ctx.QueryBool("template"))
}
if ctx.QueryBool("exclusive") {
opts.Collaborate = util.OptionalBoolFalse
}
@ -678,6 +693,10 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
repo.IsPrivate = *opts.Private
}
if opts.Template != nil {
repo.IsTemplate = *opts.Template
}
if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateRepository", err)
return err

@ -51,8 +51,8 @@ var (
}
)
func getForkRepository(ctx *context.Context) *models.Repository {
forkRepo, err := models.GetRepositoryByID(ctx.ParamsInt64(":repoid"))
func getRepository(ctx *context.Context, repoID int64) *models.Repository {
repo, err := models.GetRepositoryByID(repoID)
if err != nil {
if models.IsErrRepoNotExist(err) {
ctx.NotFound("GetRepositoryByID", nil)
@ -62,25 +62,33 @@ func getForkRepository(ctx *context.Context) *models.Repository {
return nil
}
perm, err := models.GetUserRepoPermission(forkRepo, ctx.User)
perm, err := models.GetUserRepoPermission(repo, ctx.User)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return nil
}
if forkRepo.IsEmpty || !perm.CanRead(models.UnitTypeCode) {
if log.IsTrace() {
if forkRepo.IsEmpty {
log.Trace("Empty fork repository %-v", forkRepo)
} else {
log.Trace("Permission Denied: User %-v cannot read %-v of forkRepo %-v\n"+
"User in forkRepo has Permissions: %-+v",
if !perm.CanRead(models.UnitTypeCode) {
log.Trace("Permission Denied: User %-v cannot read %-v of repo %-v\n"+
"User in repo has Permissions: %-+v",
ctx.User,
models.UnitTypeCode,
ctx.Repo,
perm)
ctx.NotFound("getRepository", nil)
return nil
}
return repo
}
func getForkRepository(ctx *context.Context) *models.Repository {
forkRepo := getRepository(ctx, ctx.ParamsInt64(":repoid"))
if ctx.Written() {
return nil
}
if forkRepo.IsEmpty {
log.Trace("Empty repository %-v", forkRepo)
ctx.NotFound("getForkRepository", nil)
return nil
}
@ -90,7 +98,7 @@ func getForkRepository(ctx *context.Context) *models.Repository {
ctx.Data["IsPrivate"] = forkRepo.IsPrivate
canForkToUser := forkRepo.OwnerID != ctx.User.ID && !ctx.User.HasForkedRepo(forkRepo.ID)
if err = forkRepo.GetOwner(); err != nil {
if err := forkRepo.GetOwner(); err != nil {
ctx.ServerError("GetOwner", err)
return nil
}
@ -109,6 +117,7 @@ func getForkRepository(ctx *context.Context) *models.Repository {
}
var traverseParentRepo = forkRepo
var err error
for {
if ctx.User.ID == traverseParentRepo.OwnerID {
canForkToUser = false

@ -129,6 +129,16 @@ func Create(ctx *context.Context) {
}
ctx.Data["ContextUser"] = ctxUser
ctx.Data["repo_template_name"] = ctx.Tr("repo.template_select")
templateID := ctx.QueryInt64("template_id")
if templateID > 0 {
templateRepo, err := models.GetRepositoryByID(templateID)
if err == nil && templateRepo.CheckUnitUser(ctxUser.ID, ctxUser.IsAdmin, models.UnitTypeCode) {
ctx.Data["repo_template"] = templateID
ctx.Data["repo_template_name"] = templateRepo.Name
}
}
ctx.HTML(200, tplCreate)
}
@ -170,6 +180,38 @@ func CreatePost(ctx *context.Context, form auth.CreateRepoForm) {
return
}
var err error
if form.RepoTemplate > 0 {
opts := models.GenerateRepoOptions{
Name: form.RepoName,
Description: form.Description,
Private: form.Private,
GitContent: form.GitContent,
Topics: form.Topics,
}
if !opts.IsValid() {
ctx.RenderWithErr(ctx.Tr("repo.template.one_item"), tplCreate, form)
return
}
templateRepo := getRepository(ctx, form.RepoTemplate)
if ctx.Written() {
return
}
if !templateRepo.IsTemplate {
ctx.RenderWithErr(ctx.Tr("repo.template.invalid"), tplCreate, form)
return
}
repo, err := repo_service.GenerateRepository(ctx.User, ctxUser, templateRepo, opts)
if err == nil {
log.Trace("Repository generated [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name)
ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name)
return
}
} else {
repo, err := repo_service.CreateRepository(ctx.User, ctxUser, models.CreateRepoOptions{
Name: form.RepoName,
Description: form.Description,
@ -185,6 +227,7 @@ func CreatePost(ctx *context.Context, form auth.CreateRepoForm) {
ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name)
return
}
}
handleCreateError(ctx, ctxUser, err, "CreatePost", tplCreate, &form)
}

@ -101,6 +101,7 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
repo.LowerName = strings.ToLower(newRepoName)
repo.Description = form.Description
repo.Website = form.Website
repo.IsTemplate = form.Template
// Visibility of forked repository is forced sync with base repository.
if repo.IsFork {

@ -44,6 +44,21 @@ func ForkRepository(doer, u *models.User, oldRepo *models.Repository, name, desc
return repo, nil
}
// GenerateRepository generates a repository from a template
func GenerateRepository(doer, u *models.User, oldRepo *models.Repository, opts models.GenerateRepoOptions) (*models.Repository, error) {
repo, err := models.GenerateRepository(doer, u, oldRepo, opts)
if err != nil {
if repo != nil {
if errDelete := models.DeleteRepository(doer, u.ID, repo.ID); errDelete != nil {
log.Error("Rollback deleteRepository: %v", errDelete)
}
}
return nil, err
}
return repo, nil
}
// DeleteRepository deletes a repository for a user or organization.
func DeleteRepository(doer *models.User, repo *models.Repository) error {
if err := models.DeleteRepository(doer, repo.OwnerID, repo.ID); err != nil {

@ -55,7 +55,34 @@
<label for="description">{{.i18n.Tr "repo.repo_desc"}}</label>
<textarea id="description" name="description">{{.description}}</textarea>
</div>
<div class="inline field">
<label>{{.i18n.Tr "repo.template"}}</label>
<div id="repo_template_search" class="ui search normal selection dropdown">
<input type="hidden" id="repo_template" name="repo_template" value="{{.repo_template}}">
<div class="default text">{{.repo_template_name}}</div>
<div class="menu">
</div>
</div>
</div>
<div id="template_units" style="display: none;">
<div class="inline field">
<label>{{.i18n.Tr "repo.template.items"}}</label>
<div class="ui checkbox">
<input class="hidden" name="git_content" type="checkbox" tabindex="0" {{if .git_content}}checked{{end}}>
<label>{{.i18n.Tr "repo.template.git_content"}}</label>
</div>
</div>
<div class="inline field">
<label></label>
<div class="ui checkbox">
<input class="hidden" name="topics" type="checkbox" tabindex="0" {{if .topics}}checked{{end}}>
<label>{{.i18n.Tr "repo.template.topics"}}</label>
</div>
</div>
</div>
<div id="non_template">
<div class="inline field">
<label>{{.i18n.Tr "repo.issue_labels"}}</label>
<div class="ui search normal selection dropdown">
@ -116,7 +143,9 @@
<label>{{.i18n.Tr "repo.auto_init"}}</label>
</div>
</div>
</div>
<br/>
<div class="inline field">
<label></label>
<button class="ui green button">

@ -12,9 +12,11 @@
<div class="divider"> / </div>
<a href="{{$.RepoLink}}">{{.Name}}</a>
{{if and .RelAvatarLink .IsPrivate}}<i class="mega-octicon octicon-lock"></i>{{end}}
{{if .IsTemplate}}<i class="icon fa-copy"></i>{{end}}
{{if .IsArchived}}<i class="archive icon archived-icon"></i>{{end}}
{{if .IsMirror}}<div class="fork-flag">{{$.i18n.Tr "repo.mirror_from"}} <a target="_blank" rel="noopener noreferrer" href="{{MirrorAddress $.Mirror}}">{{MirrorAddress $.Mirror}}</a></div>{{end}}
{{if .IsFork}}<div class="fork-flag">{{$.i18n.Tr "repo.forked_from"}} <a href="{{.BaseRepo.Link}}">{{SubStr .BaseRepo.RelLink 1 -1}}</a></div>{{end}}
{{if .IsGenerated}}<div class="fork-flag">{{$.i18n.Tr "repo.generated_from"}} <a href="{{.TemplateRepo.Link}}">{{SubStr .TemplateRepo.RelLink 1 -1}}</a></div>{{end}}
</div>
{{if not .IsBeingCreated}}
<div class="repo-buttons">

@ -94,6 +94,17 @@
</div>
</div>
<div class="fitted item">
{{if eq $n 0}}
{{if .Repository.IsTemplate}}
<div class="ui tiny blue buttons">
<a href="{{AppSubUrl}}/repo/create?template_id={{.Repository.ID}}" class="ui button">
{{.i18n.Tr "repo.use_template"}}
</a>
</div>
{{end}}
{{end}}
</div>
<div class="fitted item">
<!-- Only show clone panel in repository home page -->

@ -15,6 +15,13 @@
<label for="repo_name">{{.i18n.Tr "repo.repo_name"}}</label>
<input id="repo_name" name="repo_name" value="{{.Repository.Name}}" data-repo-name="{{.Repository.Name}}" autofocus required>
</div>
<div class="inline field">
<label>{{.i18n.Tr "repo.template"}}</label>
<div class="ui checkbox">
<input name="template" type="checkbox" {{if .Repository.IsTemplate}}checked{{end}}>
<label>{{.i18n.Tr "repo.template_helper"}}</label>
</div>
</div>
{{if not .Repository.IsFork}}
<div class="inline field">
<label>{{.i18n.Tr "repo.visibility"}}</label>

@ -1226,6 +1226,13 @@
"name": "uid",
"in": "query"
},
{
"type": "integer",
"format": "int64",
"description": "repo owner to prioritize in the results",
"name": "priority_owner_id",
"in": "query"
},
{
"type": "integer",
"format": "int64",
@ -1239,6 +1246,12 @@
"name": "private",
"in": "query"
},
{
"type": "boolean",
"description": "include template repositories this user has access to (defaults to true)",
"name": "template",
"in": "query"
},
{
"type": "integer",
"description": "page number of results to return (1-based)",
@ -8786,6 +8799,11 @@
"type": "boolean",
"x-go-name": "Private"
},
"template": {
"description": "either `true` to make this repository a template or `false` to make it a normal repository",
"type": "boolean",
"x-go-name": "Template"
},
"website": {
"description": "a URL with more information about the repository.",
"type": "string",
@ -10306,6 +10324,10 @@
"format": "int64",
"x-go-name": "Stars"
},
"template": {
"type": "boolean",
"x-go-name": "Template"
},
"updated_at": {
"type": "string",
"format": "date-time",

Loading…
Cancel
Save