Browse Source

Various wiki bug fixes (#2996)

* Update macaron

* Various wiki bug fixes
Ethan Koenig 1 year ago
parent
commit
b7ebaf6d20
40 changed files with 1085 additions and 379 deletions
  1. 1 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/HEAD
  2. 4 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/config
  3. 1 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/description
  4. 15 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/applypatch-msg.sample
  5. 24 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/commit-msg.sample
  6. 8 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/post-update.sample
  7. 14 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/pre-applypatch.sample
  8. 49 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/pre-commit.sample
  9. 53 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/pre-push.sample
  10. 169 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/pre-rebase.sample
  11. 36 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/prepare-commit-msg.sample
  12. 128 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/update.sample
  13. 6 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/info/exclude
  14. BIN
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/objects/2c/54faec6c45d31c1abfaecdab471eac6633738a
  15. BIN
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/objects/e5/3d079e581fbfdea1075a54d5b621eab0090e52
  16. BIN
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/objects/ea/82fc8777a24b07c26b3a4bf4e2742c03733eab
  17. 1 0
      integrations/gitea-repositories-meta/user2/repo1.wiki.git/refs/heads/master
  18. 16 1
      models/error.go
  19. 2 2
      models/twofactor.go
  20. 55 42
      models/wiki.go
  21. 135 13
      models/wiki_test.go
  22. 2 1
      modules/context/context.go
  23. 2 0
      modules/templates/helper.go
  24. 1 0
      options/locale/locale_en-US.ini
  25. 125 241
      routers/repo/wiki.go
  26. 0 1
      routers/routes/routes.go
  27. 1 1
      templates/repo/wiki/pages.tmpl
  28. 4 4
      templates/repo/wiki/view.tmpl
  29. 10 0
      vendor/github.com/Unknwon/com/convert.go
  30. 31 21
      vendor/github.com/Unknwon/com/string.go
  31. 1 1
      vendor/gopkg.in/macaron.v1/LICENSE
  32. 4 3
      vendor/gopkg.in/macaron.v1/README.md
  33. 23 11
      vendor/gopkg.in/macaron.v1/context.go
  34. 10 1
      vendor/gopkg.in/macaron.v1/logger.go
  35. 55 12
      vendor/gopkg.in/macaron.v1/macaron.go
  36. 22 7
      vendor/gopkg.in/macaron.v1/router.go
  37. 22 11
      vendor/gopkg.in/macaron.v1/tree.go
  38. 25 0
      vendor/gopkg.in/macaron.v1/util_go17.go
  39. 24 0
      vendor/gopkg.in/macaron.v1/util_go18.go
  40. 6 6
      vendor/vendor.json

+ 1 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/HEAD

@@ -0,0 +1 @@
1
+ref: refs/heads/master

+ 4 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/config

@@ -0,0 +1,4 @@
1
+[core]
2
+	repositoryformatversion = 0
3
+	filemode = true
4
+	bare = true

+ 1 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/description

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

+ 15 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/applypatch-msg.sample

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

+ 24 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/commit-msg.sample

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

+ 8 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/post-update.sample

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

+ 14 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/pre-applypatch.sample

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

+ 49 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/pre-commit.sample

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

+ 53 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/pre-push.sample

@@ -0,0 +1,53 @@
1
+#!/bin/sh
2
+
3
+# An example hook script to verify what is about to be pushed.  Called by "git
4
+# push" after it has checked the remote status, but before anything has been
5
+# pushed.  If this script exits with a non-zero status nothing will be pushed.
6
+#
7
+# This hook is called with the following parameters:
8
+#
9
+# $1 -- Name of the remote to which the push is being done
10
+# $2 -- URL to which the push is being done
11
+#
12
+# If pushing without using a named remote those arguments will be equal.
13
+#
14
+# Information about the commits which are being pushed is supplied as lines to
15
+# the standard input in the form:
16
+#
17
+#   <local ref> <local sha1> <remote ref> <remote sha1>
18
+#
19
+# This sample shows how to prevent push of commits where the log message starts
20
+# with "WIP" (work in progress).
21
+
22
+remote="$1"
23
+url="$2"
24
+
25
+z40=0000000000000000000000000000000000000000
26
+
27
+while read local_ref local_sha remote_ref remote_sha
28
+do
29
+	if [ "$local_sha" = $z40 ]
30
+	then
31
+		# Handle delete
32
+		:
33
+	else
34
+		if [ "$remote_sha" = $z40 ]
35
+		then
36
+			# New branch, examine all commits
37
+			range="$local_sha"
38
+		else
39
+			# Update to existing branch, examine new commits
40
+			range="$remote_sha..$local_sha"
41
+		fi
42
+
43
+		# Check for WIP commit
44
+		commit=`git rev-list -n 1 --grep '^WIP' "$range"`
45
+		if [ -n "$commit" ]
46
+		then
47
+			echo >&2 "Found WIP commit in $local_ref, not pushing"
48
+			exit 1
49
+		fi
50
+	fi
51
+done
52
+
53
+exit 0

+ 169 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/pre-rebase.sample

@@ -0,0 +1,169 @@
1
+#!/bin/sh
2
+#
3
+# Copyright (c) 2006, 2008 Junio C Hamano
4
+#
5
+# The "pre-rebase" hook is run just before "git rebase" starts doing
6
+# its job, and can prevent the command from running by exiting with
7
+# non-zero status.
8
+#
9
+# The hook is called with the following parameters:
10
+#
11
+# $1 -- the upstream the series was forked from.
12
+# $2 -- the branch being rebased (or empty when rebasing the current branch).
13
+#
14
+# This sample shows how to prevent topic branches that are already
15
+# merged to 'next' branch from getting rebased, because allowing it
16
+# would result in rebasing already published history.
17
+
18
+publish=next
19
+basebranch="$1"
20
+if test "$#" = 2
21
+then
22
+	topic="refs/heads/$2"
23
+else
24
+	topic=`git symbolic-ref HEAD` ||
25
+	exit 0 ;# we do not interrupt rebasing detached HEAD
26
+fi
27
+
28
+case "$topic" in
29
+refs/heads/??/*)
30
+	;;
31
+*)
32
+	exit 0 ;# we do not interrupt others.
33
+	;;
34
+esac
35
+
36
+# Now we are dealing with a topic branch being rebased
37
+# on top of master.  Is it OK to rebase it?
38
+
39
+# Does the topic really exist?
40
+git show-ref -q "$topic" || {
41
+	echo >&2 "No such branch $topic"
42
+	exit 1
43
+}
44
+
45
+# Is topic fully merged to master?
46
+not_in_master=`git rev-list --pretty=oneline ^master "$topic"`
47
+if test -z "$not_in_master"
48
+then
49
+	echo >&2 "$topic is fully merged to master; better remove it."
50
+	exit 1 ;# we could allow it, but there is no point.
51
+fi
52
+
53
+# Is topic ever merged to next?  If so you should not be rebasing it.
54
+only_next_1=`git rev-list ^master "^$topic" ${publish} | sort`
55
+only_next_2=`git rev-list ^master           ${publish} | sort`
56
+if test "$only_next_1" = "$only_next_2"
57
+then
58
+	not_in_topic=`git rev-list "^$topic" master`
59
+	if test -z "$not_in_topic"
60
+	then
61
+		echo >&2 "$topic is already up-to-date with master"
62
+		exit 1 ;# we could allow it, but there is no point.
63
+	else
64
+		exit 0
65
+	fi
66
+else
67
+	not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"`
68
+	/usr/bin/perl -e '
69
+		my $topic = $ARGV[0];
70
+		my $msg = "* $topic has commits already merged to public branch:\n";
71
+		my (%not_in_next) = map {
72
+			/^([0-9a-f]+) /;
73
+			($1 => 1);
74
+		} split(/\n/, $ARGV[1]);
75
+		for my $elem (map {
76
+				/^([0-9a-f]+) (.*)$/;
77
+				[$1 => $2];
78
+			} split(/\n/, $ARGV[2])) {
79
+			if (!exists $not_in_next{$elem->[0]}) {
80
+				if ($msg) {
81
+					print STDERR $msg;
82
+					undef $msg;
83
+				}
84
+				print STDERR " $elem->[1]\n";
85
+			}
86
+		}
87
+	' "$topic" "$not_in_next" "$not_in_master"
88
+	exit 1
89
+fi
90
+
91
+<<\DOC_END
92
+
93
+This sample hook safeguards topic branches that have been
94
+published from being rewound.
95
+
96
+The workflow assumed here is:
97
+
98
+ * Once a topic branch forks from "master", "master" is never
99
+   merged into it again (either directly or indirectly).
100
+
101
+ * Once a topic branch is fully cooked and merged into "master",
102
+   it is deleted.  If you need to build on top of it to correct
103
+   earlier mistakes, a new topic branch is created by forking at
104
+   the tip of the "master".  This is not strictly necessary, but
105
+   it makes it easier to keep your history simple.
106
+
107
+ * Whenever you need to test or publish your changes to topic
108
+   branches, merge them into "next" branch.
109
+
110
+The script, being an example, hardcodes the publish branch name
111
+to be "next", but it is trivial to make it configurable via
112
+$GIT_DIR/config mechanism.
113
+
114
+With this workflow, you would want to know:
115
+
116
+(1) ... if a topic branch has ever been merged to "next".  Young
117
+    topic branches can have stupid mistakes you would rather
118
+    clean up before publishing, and things that have not been
119
+    merged into other branches can be easily rebased without
120
+    affecting other people.  But once it is published, you would
121
+    not want to rewind it.
122
+
123
+(2) ... if a topic branch has been fully merged to "master".
124
+    Then you can delete it.  More importantly, you should not
125
+    build on top of it -- other people may already want to
126
+    change things related to the topic as patches against your
127
+    "master", so if you need further changes, it is better to
128
+    fork the topic (perhaps with the same name) afresh from the
129
+    tip of "master".
130
+
131
+Let's look at this example:
132
+
133
+		   o---o---o---o---o---o---o---o---o---o "next"
134
+		  /       /           /           /
135
+		 /   a---a---b A     /           /
136
+		/   /               /           /
137
+	       /   /   c---c---c---c B         /
138
+	      /   /   /             \         /
139
+	     /   /   /   b---b C     \       /
140
+	    /   /   /   /             \     /
141
+    ---o---o---o---o---o---o---o---o---o---o---o "master"
142
+
143
+
144
+A, B and C are topic branches.
145
+
146
+ * A has one fix since it was merged up to "next".
147
+
148
+ * B has finished.  It has been fully merged up to "master" and "next",
149
+   and is ready to be deleted.
150
+
151
+ * C has not merged to "next" at all.
152
+
153
+We would want to allow C to be rebased, refuse A, and encourage
154
+B to be deleted.
155
+
156
+To compute (1):
157
+
158
+	git rev-list ^master ^topic next
159
+	git rev-list ^master        next
160
+
161
+	if these match, topic has not merged in next at all.
162
+
163
+To compute (2):
164
+
165
+	git rev-list master..topic
166
+
167
+	if this is empty, it is fully merged to "master".
168
+
169
+DOC_END

+ 36 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/prepare-commit-msg.sample

@@ -0,0 +1,36 @@
1
+#!/bin/sh
2
+#
3
+# An example hook script to prepare the commit log message.
4
+# Called by "git commit" with the name of the file that has the
5
+# commit message, followed by the description of the commit
6
+# message's source.  The hook's purpose is to edit the commit
7
+# message file.  If the hook fails with a non-zero status,
8
+# the commit is aborted.
9
+#
10
+# To enable this hook, rename this file to "prepare-commit-msg".
11
+
12
+# This hook includes three examples.  The first comments out the
13
+# "Conflicts:" part of a merge commit.
14
+#
15
+# The second includes the output of "git diff --name-status -r"
16
+# into the message, just before the "git status" output.  It is
17
+# commented because it doesn't cope with --amend or with squashed
18
+# commits.
19
+#
20
+# The third example adds a Signed-off-by line to the message, that can
21
+# still be edited.  This is rarely a good idea.
22
+
23
+case "$2,$3" in
24
+  merge,)
25
+    /usr/bin/perl -i.bak -ne 's/^/# /, s/^# #/#/ if /^Conflicts/ .. /#/; print' "$1" ;;
26
+
27
+# ,|template,)
28
+#   /usr/bin/perl -i.bak -pe '
29
+#      print "\n" . `git diff --cached --name-status -r`
30
+#	 if /^#/ && $first++ == 0' "$1" ;;
31
+
32
+  *) ;;
33
+esac
34
+
35
+# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
36
+# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"

+ 128 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/hooks/update.sample

@@ -0,0 +1,128 @@
1
+#!/bin/sh
2
+#
3
+# An example hook script to block unannotated tags from entering.
4
+# Called by "git receive-pack" with arguments: refname sha1-old sha1-new
5
+#
6
+# To enable this hook, rename this file to "update".
7
+#
8
+# Config
9
+# ------
10
+# hooks.allowunannotated
11
+#   This boolean sets whether unannotated tags will be allowed into the
12
+#   repository.  By default they won't be.
13
+# hooks.allowdeletetag
14
+#   This boolean sets whether deleting tags will be allowed in the
15
+#   repository.  By default they won't be.
16
+# hooks.allowmodifytag
17
+#   This boolean sets whether a tag may be modified after creation. By default
18
+#   it won't be.
19
+# hooks.allowdeletebranch
20
+#   This boolean sets whether deleting branches will be allowed in the
21
+#   repository.  By default they won't be.
22
+# hooks.denycreatebranch
23
+#   This boolean sets whether remotely creating branches will be denied
24
+#   in the repository.  By default this is allowed.
25
+#
26
+
27
+# --- Command line
28
+refname="$1"
29
+oldrev="$2"
30
+newrev="$3"
31
+
32
+# --- Safety check
33
+if [ -z "$GIT_DIR" ]; then
34
+	echo "Don't run this script from the command line." >&2
35
+	echo " (if you want, you could supply GIT_DIR then run" >&2
36
+	echo "  $0 <ref> <oldrev> <newrev>)" >&2
37
+	exit 1
38
+fi
39
+
40
+if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then
41
+	echo "usage: $0 <ref> <oldrev> <newrev>" >&2
42
+	exit 1
43
+fi
44
+
45
+# --- Config
46
+allowunannotated=$(git config --bool hooks.allowunannotated)
47
+allowdeletebranch=$(git config --bool hooks.allowdeletebranch)
48
+denycreatebranch=$(git config --bool hooks.denycreatebranch)
49
+allowdeletetag=$(git config --bool hooks.allowdeletetag)
50
+allowmodifytag=$(git config --bool hooks.allowmodifytag)
51
+
52
+# check for no description
53
+projectdesc=$(sed -e '1q' "$GIT_DIR/description")
54
+case "$projectdesc" in
55
+"Unnamed repository"* | "")
56
+	echo "*** Project description file hasn't been set" >&2
57
+	exit 1
58
+	;;
59
+esac
60
+
61
+# --- Check types
62
+# if $newrev is 0000...0000, it's a commit to delete a ref.
63
+zero="0000000000000000000000000000000000000000"
64
+if [ "$newrev" = "$zero" ]; then
65
+	newrev_type=delete
66
+else
67
+	newrev_type=$(git cat-file -t $newrev)
68
+fi
69
+
70
+case "$refname","$newrev_type" in
71
+	refs/tags/*,commit)
72
+		# un-annotated tag
73
+		short_refname=${refname##refs/tags/}
74
+		if [ "$allowunannotated" != "true" ]; then
75
+			echo "*** The un-annotated tag, $short_refname, is not allowed in this repository" >&2
76
+			echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2
77
+			exit 1
78
+		fi
79
+		;;
80
+	refs/tags/*,delete)
81
+		# delete tag
82
+		if [ "$allowdeletetag" != "true" ]; then
83
+			echo "*** Deleting a tag is not allowed in this repository" >&2
84
+			exit 1
85
+		fi
86
+		;;
87
+	refs/tags/*,tag)
88
+		# annotated tag
89
+		if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1
90
+		then
91
+			echo "*** Tag '$refname' already exists." >&2
92
+			echo "*** Modifying a tag is not allowed in this repository." >&2
93
+			exit 1
94
+		fi
95
+		;;
96
+	refs/heads/*,commit)
97
+		# branch
98
+		if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then
99
+			echo "*** Creating a branch is not allowed in this repository" >&2
100
+			exit 1
101
+		fi
102
+		;;
103
+	refs/heads/*,delete)
104
+		# delete branch
105
+		if [ "$allowdeletebranch" != "true" ]; then
106
+			echo "*** Deleting a branch is not allowed in this repository" >&2
107
+			exit 1
108
+		fi
109
+		;;
110
+	refs/remotes/*,commit)
111
+		# tracking branch
112
+		;;
113
+	refs/remotes/*,delete)
114
+		# delete tracking branch
115
+		if [ "$allowdeletebranch" != "true" ]; then
116
+			echo "*** Deleting a tracking branch is not allowed in this repository" >&2
117
+			exit 1
118
+		fi
119
+		;;
120
+	*)
121
+		# Anything else (is there anything else?)
122
+		echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2
123
+		exit 1
124
+		;;
125
+esac
126
+
127
+# --- Finished
128
+exit 0

+ 6 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/info/exclude

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

BIN
integrations/gitea-repositories-meta/user2/repo1.wiki.git/objects/2c/54faec6c45d31c1abfaecdab471eac6633738a


BIN
integrations/gitea-repositories-meta/user2/repo1.wiki.git/objects/e5/3d079e581fbfdea1075a54d5b621eab0090e52


BIN
integrations/gitea-repositories-meta/user2/repo1.wiki.git/objects/ea/82fc8777a24b07c26b3a4bf4e2742c03733eab


+ 1 - 0
integrations/gitea-repositories-meta/user2/repo1.wiki.git/refs/heads/master

@@ -0,0 +1 @@
1
+2c54faec6c45d31c1abfaecdab471eac6633738a

+ 16 - 1
models/error.go

@@ -191,7 +191,7 @@ type ErrWikiAlreadyExist struct {
191 191
 	Title string
192 192
 }
193 193
 
194
-// IsErrWikiAlreadyExist checks if an error is a ErrWikiAlreadyExist.
194
+// IsErrWikiAlreadyExist checks if an error is an ErrWikiAlreadyExist.
195 195
 func IsErrWikiAlreadyExist(err error) bool {
196 196
 	_, ok := err.(ErrWikiAlreadyExist)
197 197
 	return ok
@@ -201,6 +201,21 @@ func (err ErrWikiAlreadyExist) Error() string {
201 201
 	return fmt.Sprintf("wiki page already exists [title: %s]", err.Title)
202 202
 }
203 203
 
204
+// ErrWikiReservedName represents a reserved name error.
205
+type ErrWikiReservedName struct {
206
+	Title string
207
+}
208
+
209
+// IsErrWikiReservedName checks if an error is an ErrWikiReservedName.
210
+func IsErrWikiReservedName(err error) bool {
211
+	_, ok := err.(ErrWikiReservedName)
212
+	return ok
213
+}
214
+
215
+func (err ErrWikiReservedName) Error() string {
216
+	return fmt.Sprintf("wiki title is reserved: %s", err.Title)
217
+}
218
+
204 219
 // __________     ___.   .__  .__          ____  __.
205 220
 // \______   \__ _\_ |__ |  | |__| ____   |    |/ _|____ ___.__.
206 221
 //  |     ___/  |  \ __ \|  | |  |/ ___\  |      <_/ __ <   |  |

+ 2 - 2
models/twofactor.go

@@ -61,7 +61,7 @@ func (t *TwoFactor) getEncryptionKey() []byte {
61 61
 
62 62
 // SetSecret sets the 2FA secret.
63 63
 func (t *TwoFactor) SetSecret(secret string) error {
64
-	secretBytes, err := com.AESEncrypt(t.getEncryptionKey(), []byte(secret))
64
+	secretBytes, err := com.AESGCMEncrypt(t.getEncryptionKey(), []byte(secret))
65 65
 	if err != nil {
66 66
 		return err
67 67
 	}
@@ -75,7 +75,7 @@ func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
75 75
 	if err != nil {
76 76
 		return false, err
77 77
 	}
78
-	secret, err := com.AESDecrypt(t.getEncryptionKey(), decodedStoredSecret)
78
+	secret, err := com.AESGCMDecrypt(t.getEncryptionKey(), decodedStoredSecret)
79 79
 	if err != nil {
80 80
 		return false, err
81 81
 	}

+ 55 - 42
models/wiki.go

@@ -22,22 +22,37 @@ import (
22 22
 )
23 23
 
24 24
 var (
25
-	reservedWikiPaths = []string{"_pages", "_new", "_edit"}
25
+	reservedWikiNames = []string{"_pages", "_new", "_edit"}
26 26
 	wikiWorkingPool   = sync.NewExclusivePool()
27 27
 )
28 28
 
29
-// ToWikiPageURL formats a string to corresponding wiki URL name.
30
-func ToWikiPageURL(name string) string {
29
+// NormalizeWikiName normalizes a wiki name
30
+func NormalizeWikiName(name string) string {
31
+	return strings.Replace(name, "-", " ", -1)
32
+}
33
+
34
+// WikiNameToSubURL converts a wiki name to its corresponding sub-URL.
35
+func WikiNameToSubURL(name string) string {
31 36
 	return url.QueryEscape(strings.Replace(name, " ", "-", -1))
32 37
 }
33 38
 
34
-// ToWikiPageName formats a URL back to corresponding wiki page name,
35
-// and removes leading characters './' to prevent changing files
36
-// that are not belong to wiki repository.
37
-func ToWikiPageName(urlString string) string {
38
-	name, _ := url.QueryUnescape(strings.Replace(urlString, "-", " ", -1))
39
-	name = strings.Replace(name, "\t", " ", -1)
40
-	return strings.Replace(strings.TrimLeft(name, "./"), "/", " ", -1)
39
+// WikiNameToFilename converts a wiki name to its corresponding filename.
40
+func WikiNameToFilename(name string) string {
41
+	name = strings.Replace(name, " ", "-", -1)
42
+	return url.QueryEscape(name) + ".md"
43
+}
44
+
45
+// WikiFilenameToName converts a wiki filename to its corresponding page name.
46
+func WikiFilenameToName(filename string) (string, error) {
47
+	if !strings.HasSuffix(filename, ".md") {
48
+		return "", fmt.Errorf("Invalid wiki filename: %s", filename)
49
+	}
50
+	basename := filename[:len(filename)-3]
51
+	unescaped, err := url.QueryUnescape(basename)
52
+	if err != nil {
53
+		return "", err
54
+	}
55
+	return NormalizeWikiName(unescaped), nil
41 56
 }
42 57
 
43 58
 // WikiCloneLink returns clone URLs of repository wiki.
@@ -81,7 +96,7 @@ func (repo *Repository) LocalWikiPath() string {
81 96
 }
82 97
 
83 98
 // UpdateLocalWiki makes sure the local copy of repository wiki is up-to-date.
84
-func (repo *Repository) UpdateLocalWiki() error {
99
+func (repo *Repository) updateLocalWiki() error {
85 100
 	// Don't pass branch name here because it fails to clone and
86 101
 	// checkout to a specific branch when wiki is an empty repository.
87 102
 	var branch = ""
@@ -95,19 +110,19 @@ func discardLocalWikiChanges(localPath string) error {
95 110
 	return discardLocalRepoBranchChanges(localPath, "master")
96 111
 }
97 112
 
98
-// pathAllowed checks if a wiki path is allowed
99
-func pathAllowed(path string) error {
100
-	for i := range reservedWikiPaths {
101
-		if path == reservedWikiPaths[i] {
102
-			return ErrWikiAlreadyExist{path}
113
+// nameAllowed checks if a wiki name is allowed
114
+func nameAllowed(name string) error {
115
+	for _, reservedName := range reservedWikiNames {
116
+		if name == reservedName {
117
+			return ErrWikiReservedName{name}
103 118
 		}
104 119
 	}
105 120
 	return nil
106 121
 }
107 122
 
108
-// updateWikiPage adds new page to repository wiki.
109
-func (repo *Repository) updateWikiPage(doer *User, oldWikiPath, wikiPath, content, message string, isNew bool) (err error) {
110
-	if err = pathAllowed(wikiPath); err != nil {
123
+// updateWikiPage adds a new page to the repository wiki.
124
+func (repo *Repository) updateWikiPage(doer *User, oldWikiName, newWikiName, content, message string, isNew bool) (err error) {
125
+	if err = nameAllowed(newWikiName); err != nil {
111 126
 		return err
112 127
 	}
113 128
 
@@ -121,23 +136,21 @@ func (repo *Repository) updateWikiPage(doer *User, oldWikiPath, wikiPath, conten
121 136
 	localPath := repo.LocalWikiPath()
122 137
 	if err = discardLocalWikiChanges(localPath); err != nil {
123 138
 		return fmt.Errorf("discardLocalWikiChanges: %v", err)
124
-	} else if err = repo.UpdateLocalWiki(); err != nil {
139
+	} else if err = repo.updateLocalWiki(); err != nil {
125 140
 		return fmt.Errorf("UpdateLocalWiki: %v", err)
126 141
 	}
127 142
 
128
-	title := ToWikiPageName(wikiPath)
129
-	filename := path.Join(localPath, wikiPath+".md")
143
+	newWikiPath := path.Join(localPath, WikiNameToFilename(newWikiName))
130 144
 
131 145
 	// If not a new file, show perform update not create.
132 146
 	if isNew {
133
-		if com.IsExist(filename) {
134
-			return ErrWikiAlreadyExist{filename}
147
+		if com.IsExist(newWikiPath) {
148
+			return ErrWikiAlreadyExist{newWikiPath}
135 149
 		}
136 150
 	} else {
137
-		file := path.Join(localPath, oldWikiPath+".md")
138
-
139
-		if err := os.Remove(file); err != nil {
140
-			return fmt.Errorf("Failed to remove %s: %v", file, err)
151
+		oldWikiPath := path.Join(localPath, WikiNameToFilename(oldWikiName))
152
+		if err := os.Remove(oldWikiPath); err != nil {
153
+			return fmt.Errorf("Failed to remove %s: %v", oldWikiPath, err)
141 154
 		}
142 155
 	}
143 156
 
@@ -146,15 +159,16 @@ func (repo *Repository) updateWikiPage(doer *User, oldWikiPath, wikiPath, conten
146 159
 	// as a new page operation.
147 160
 	// So we want to make sure the symlink is removed before write anything.
148 161
 	// The new file we created will be in normal text format.
162
+	if err = os.RemoveAll(newWikiPath); err != nil {
163
+		return err
164
+	}
149 165
 
150
-	_ = os.Remove(filename)
151
-
152
-	if err = ioutil.WriteFile(filename, []byte(content), 0666); err != nil {
166
+	if err = ioutil.WriteFile(newWikiPath, []byte(content), 0666); err != nil {
153 167
 		return fmt.Errorf("WriteFile: %v", err)
154 168
 	}
155 169
 
156 170
 	if len(message) == 0 {
157
-		message = "Update page '" + title + "'"
171
+		message = "Update page '" + newWikiName + "'"
158 172
 	}
159 173
 	if err = git.AddChanges(localPath, true); err != nil {
160 174
 		return fmt.Errorf("AddChanges: %v", err)
@@ -174,36 +188,35 @@ func (repo *Repository) updateWikiPage(doer *User, oldWikiPath, wikiPath, conten
174 188
 }
175 189
 
176 190
 // AddWikiPage adds a new wiki page with a given wikiPath.
177
-func (repo *Repository) AddWikiPage(doer *User, wikiPath, content, message string) error {
178
-	return repo.updateWikiPage(doer, "", wikiPath, content, message, true)
191
+func (repo *Repository) AddWikiPage(doer *User, wikiName, content, message string) error {
192
+	return repo.updateWikiPage(doer, "", wikiName, content, message, true)
179 193
 }
180 194
 
181 195
 // EditWikiPage updates a wiki page identified by its wikiPath,
182 196
 // optionally also changing wikiPath.
183
-func (repo *Repository) EditWikiPage(doer *User, oldWikiPath, wikiPath, content, message string) error {
184
-	return repo.updateWikiPage(doer, oldWikiPath, wikiPath, content, message, false)
197
+func (repo *Repository) EditWikiPage(doer *User, oldWikiName, newWikiName, content, message string) error {
198
+	return repo.updateWikiPage(doer, oldWikiName, newWikiName, content, message, false)
185 199
 }
186 200
 
187
-// DeleteWikiPage deletes a wiki page identified by its wikiPath.
188
-func (repo *Repository) DeleteWikiPage(doer *User, wikiPath string) (err error) {
201
+// DeleteWikiPage deletes a wiki page identified by its path.
202
+func (repo *Repository) DeleteWikiPage(doer *User, wikiName string) (err error) {
189 203
 	wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
190 204
 	defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))
191 205
 
192 206
 	localPath := repo.LocalWikiPath()
193 207
 	if err = discardLocalWikiChanges(localPath); err != nil {
194 208
 		return fmt.Errorf("discardLocalWikiChanges: %v", err)
195
-	} else if err = repo.UpdateLocalWiki(); err != nil {
209
+	} else if err = repo.updateLocalWiki(); err != nil {
196 210
 		return fmt.Errorf("UpdateLocalWiki: %v", err)
197 211
 	}
198 212
 
199
-	filename := path.Join(localPath, wikiPath+".md")
213
+	filename := path.Join(localPath, WikiNameToFilename(wikiName))
200 214
 
201 215
 	if err := os.Remove(filename); err != nil {
202 216
 		return fmt.Errorf("Failed to remove %s: %v", filename, err)
203 217
 	}
204 218
 
205
-	title := ToWikiPageName(wikiPath)
206
-	message := "Delete page '" + title + "'"
219
+	message := "Delete page '" + wikiName + "'"
207 220
 
208 221
 	if err = git.AddChanges(localPath, true); err != nil {
209 222
 		return fmt.Errorf("AddChanges: %v", err)

+ 135 - 13
models/wiki_test.go

@@ -5,24 +5,91 @@
5 5
 package models
6 6
 
7 7
 import (
8
+	"path"
8 9
 	"path/filepath"
9 10
 	"testing"
10 11
 
11 12
 	"code.gitea.io/gitea/modules/setting"
12 13
 
14
+	"github.com/Unknwon/com"
13 15
 	"github.com/stretchr/testify/assert"
14 16
 )
15 17
 
16
-func TestToWikiPageURL(t *testing.T) {
17
-	assert.Equal(t, "wiki-name", ToWikiPageURL("wiki-name"))
18
-	assert.Equal(t, "wiki-name-with-many-spaces", ToWikiPageURL("wiki name with many spaces"))
18
+func TestNormalizeWikiName(t *testing.T) {
19
+	type test struct {
20
+		Expected string
21
+		WikiName string
22
+	}
23
+	for _, test := range []test{
24
+		{"wiki name", "wiki name"},
25
+		{"wiki name", "wiki-name"},
26
+		{"name with/slash", "name with/slash"},
27
+		{"name with%percent", "name-with%percent"},
28
+		{"%2F", "%2F"},
29
+	} {
30
+		assert.Equal(t, test.Expected, NormalizeWikiName(test.WikiName))
31
+	}
19 32
 }
20 33
 
21
-func TestToWikiPageName(t *testing.T) {
22
-	assert.Equal(t, "wiki name", ToWikiPageName("wiki name"))
23
-	assert.Equal(t, "wiki name", ToWikiPageName("wiki-name"))
24
-	assert.Equal(t, "wiki name", ToWikiPageName("wiki\tname"))
25
-	assert.Equal(t, "wiki name", ToWikiPageName("./.././wiki/name"))
34
+func TestWikiNameToFilename(t *testing.T) {
35
+	type test struct {
36
+		Expected string
37
+		WikiName string
38
+	}
39
+	for _, test := range []test{
40
+		{"wiki-name.md", "wiki name"},
41
+		{"wiki-name.md", "wiki-name"},
42
+		{"name-with%2Fslash.md", "name with/slash"},
43
+		{"name-with%25percent.md", "name with%percent"},
44
+	} {
45
+		assert.Equal(t, test.Expected, WikiNameToFilename(test.WikiName))
46
+	}
47
+}
48
+
49
+func TestWikiNameToSubURL(t *testing.T) {
50
+	type test struct {
51
+		Expected string
52
+		WikiName string
53
+	}
54
+	for _, test := range []test{
55
+		{"wiki-name", "wiki name"},
56
+		{"wiki-name", "wiki-name"},
57
+		{"name-with%2Fslash", "name with/slash"},
58
+		{"name-with%25percent", "name with%percent"},
59
+	} {
60
+		assert.Equal(t, test.Expected, WikiNameToSubURL(test.WikiName))
61
+	}
62
+}
63
+
64
+func TestWikiFilenameToName(t *testing.T) {
65
+	type test struct {
66
+		Expected string
67
+		Filename string
68
+	}
69
+	for _, test := range []test{
70
+		{"hello world", "hello-world.md"},
71
+		{"symbols/?*", "symbols%2F%3F%2A.md"},
72
+	} {
73
+		name, err := WikiFilenameToName(test.Filename)
74
+		assert.NoError(t, err)
75
+		assert.Equal(t, test.Expected, name)
76
+	}
77
+}
78
+
79
+func TestWikiNameToFilenameToName(t *testing.T) {
80
+	// converting from wiki name to filename, then back to wiki name should
81
+	// return the original (normalized) name
82
+	for _, name := range []string{
83
+		"wiki-name",
84
+		"wiki name",
85
+		"wiki name with/slash",
86
+		"$$$%%%^^&&!@#$(),.<>",
87
+	} {
88
+		filename := WikiNameToFilename(name)
89
+		resultName, err := WikiFilenameToName(filename)
90
+		assert.NoError(t, err)
91
+		assert.Equal(t, NormalizeWikiName(name), resultName)
92
+	}
26 93
 }
27 94
 
28 95
 func TestRepository_WikiCloneLink(t *testing.T) {
@@ -47,17 +114,72 @@ func TestRepository_WikiPath(t *testing.T) {
47 114
 	assert.Equal(t, expected, repo.WikiPath())
48 115
 }
49 116
 
50
-// TODO TestRepository_HasWiki
117
+func TestRepository_HasWiki(t *testing.T) {
118
+	prepareTestEnv(t)
119
+	repo1 := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
120
+	assert.True(t, repo1.HasWiki())
121
+	repo2 := AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository)
122
+	assert.False(t, repo2.HasWiki())
123
+}
124
+
125
+func TestRepository_InitWiki(t *testing.T) {
126
+	prepareTestEnv(t)
127
+	// repo1 already has a wiki
128
+	repo1 := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
129
+	assert.NoError(t, repo1.InitWiki())
51 130
 
52
-// TODO TestRepository_InitWiki
131
+	// repo2 does not already have a wiki
132
+	repo2 := AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository)
133
+	assert.NoError(t, repo2.InitWiki())
134
+	assert.True(t, repo2.HasWiki())
135
+}
53 136
 
54 137
 func TestRepository_LocalWikiPath(t *testing.T) {
55
-	assert.NoError(t, PrepareTestDatabase())
138
+	prepareTestEnv(t)
56 139
 	repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
57 140
 	expected := filepath.Join(setting.AppDataPath, "tmp/local-wiki/1")
58 141
 	assert.Equal(t, expected, repo.LocalWikiPath())
59 142
 }
60 143
 
61
-// TODO TestRepository_UpdateLocalWiki
144
+func TestRepository_AddWikiPage(t *testing.T) {
145
+	const wikiContent = "This is the wiki content"
146
+	const commitMsg = "Commit message"
147
+	repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
148
+	doer := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
149
+	for _, wikiName := range []string{
150
+		"Another page",
151
+		"Here's a <tag> and a/slash",
152
+	} {
153
+		prepareTestEnv(t)
154
+		assert.NoError(t, repo.AddWikiPage(doer, wikiName, wikiContent, commitMsg))
155
+		expectedPath := path.Join(repo.LocalWikiPath(), WikiNameToFilename(wikiName))
156
+		assert.True(t, com.IsExist(expectedPath))
157
+	}
158
+}
159
+
160
+func TestRepository_EditWikiPage(t *testing.T) {
161
+	const newWikiContent = "This is the new content"
162
+	const commitMsg = "Commit message"
163
+	repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
164
+	doer := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
165
+	for _, newWikiName := range []string{
166
+		"New home",
167
+		"New/name/with/slashes",
168
+	} {
169
+		prepareTestEnv(t)
170
+		assert.NoError(t, repo.EditWikiPage(doer, "Home", newWikiName, newWikiContent, commitMsg))
171
+		newPath := path.Join(repo.LocalWikiPath(), WikiNameToFilename(newWikiName))
172
+		assert.True(t, com.IsExist(newPath))
173
+		oldPath := path.Join(repo.LocalWikiPath(), "Home.md")
174
+		assert.False(t, com.IsExist(oldPath))
175
+	}
176
+}
62 177
 
63
-// TODO ... (all remaining untested functions)
178
+func TestRepository_DeleteWikiPage(t *testing.T) {
179
+	prepareTestEnv(t)
180
+	repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
181
+	doer := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
182
+	assert.NoError(t, repo.DeleteWikiPage(doer, "Home"))
183
+	wikiPath := path.Join(repo.LocalWikiPath(), "Home.md")
184
+	assert.False(t, com.IsExist(wikiPath))
185
+}

+ 2 - 1
modules/context/context.go

@@ -36,6 +36,7 @@ type Context struct {
36 36
 	Session session.Store
37 37
 
38 38
 	Link        string // current request URL
39
+	EscapedLink string
39 40
 	User        *models.User
40 41
 	IsSigned    bool
41 42
 	IsBasicAuth bool
@@ -157,7 +158,7 @@ func Contexter() macaron.Handler {
157 158
 			csrf:    x,
158 159
 			Flash:   f,
159 160
 			Session: sess,
160
-			Link:    setting.AppSubURL + strings.TrimSuffix(c.Req.URL.Path, "/"),
161
+			Link:    setting.AppSubURL + strings.TrimSuffix(c.Req.URL.EscapedPath(), "/"),
161 162
 			Repo: &Repository{
162 163
 				PullRequest: &PullRequest{},
163 164
 			},

+ 2 - 0
modules/templates/helper.go

@@ -11,6 +11,7 @@ import (
11 11
 	"fmt"
12 12
 	"html/template"
13 13
 	"mime"
14
+	"net/url"
14 15
 	"path/filepath"
15 16
 	"runtime"
16 17
 	"strings"
@@ -105,6 +106,7 @@ func NewFuncMap() []template.FuncMap {
105 106
 		"ShortSha":          base.ShortSha,
106 107
 		"MD5":               base.EncodeMD5,
107 108
 		"ActionContent2Commits": ActionContent2Commits,
109
+		"PathEscape":            url.PathEscape,
108 110
 		"EscapePound": func(str string) string {
109 111
 			return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
110 112
 		},

+ 1 - 0
options/locale/locale_en-US.ini

@@ -804,6 +804,7 @@ wiki.new_page_button = New Page
804 804
 wiki.delete_page_button = Delete Page
805 805
 wiki.delete_page_notice_1 = This will delete the page <code>"%s"</code>. Please make sure you want to delete this page.
806 806
 wiki.page_already_exists = A wiki page with the same name already exists.
807
+wiki.reserved_page = The wiki page name %s is reserved, please select a different name.
807 808
 wiki.pages = Pages
808 809
 wiki.last_updated = Last updated %s
809 810
 

+ 125 - 241
routers/repo/wiki.go

@@ -7,7 +7,6 @@ package repo
7 7
 import (
8 8
 	"fmt"
9 9
 	"io/ioutil"
10
-	"net/url"
11 10
 	"path/filepath"
12 11
 	"strings"
13 12
 	"time"
@@ -47,140 +46,30 @@ func MustEnableWiki(ctx *context.Context) {
47 46
 // PageMeta wiki page meat information
48 47
 type PageMeta struct {
49 48
 	Name    string
50
-	URL     string
49
+	SubURL  string
51 50
 	Updated time.Time
52 51
 }
53 52
 
54
-func urlEncoded(str string) string {
55
-	u, err := url.Parse(str)
56
-	if err != nil {
57
-		return str
58
-	}
59
-	return u.String()
60
-}
61
-func urlDecoded(str string) string {
62
-	res, err := url.QueryUnescape(str)
63
-	if err != nil {
64
-		return str
65
-	}
66
-	return res
67
-}
68
-
69
-// commitTreeBlobEntry processes found file and checks if it matches search target
70
-func commitTreeBlobEntry(entry *git.TreeEntry, path string, targets []string, textOnly bool) *git.TreeEntry {
71
-	name := entry.Name()
72
-	ext := filepath.Ext(name)
73
-	if !textOnly || markdown.IsMarkdownFile(name) || ext == ".textile" {
74
-		for _, target := range targets {
75
-			if matchName(path, target) || matchName(urlEncoded(path), target) || matchName(urlDecoded(path), target) {
76
-				return entry
77
-			}
78
-			pathNoExt := strings.TrimSuffix(path, ext)
79
-			if matchName(pathNoExt, target) || matchName(urlEncoded(pathNoExt), target) || matchName(urlDecoded(pathNoExt), target) {
80
-				return entry
81
-			}
82
-		}
83
-	}
84
-	return nil
85
-}
86
-
87
-// commitTreeDirEntry is a recursive file tree traversal function
88
-func commitTreeDirEntry(repo *git.Repository, commit *git.Commit, entries []*git.TreeEntry, prevPath string, targets []string, textOnly bool) (*git.TreeEntry, error) {
89
-	for i := range entries {
90
-		entry := entries[i]
91
-		var path string
92
-		if len(prevPath) == 0 {
93
-			path = entry.Name()
94
-		} else {
95
-			path = prevPath + "/" + entry.Name()
96
-		}
97
-		if entry.Type == git.ObjectBlob {
98
-			// File
99
-			if res := commitTreeBlobEntry(entry, path, targets, textOnly); res != nil {
100
-				return res, nil
101
-			}
102
-		} else if entry.IsDir() {
103
-			// Directory
104
-			// Get our tree entry, handling all possible errors
105
-			var err error
106
-			var tree *git.Tree
107
-			if tree, err = repo.GetTree(entry.ID.String()); tree == nil || err != nil {
108
-				if err == nil {
109
-					err = fmt.Errorf("repo.GetTree(%s) => nil", entry.ID.String())
110
-				}
111
-				return nil, err
112
-			}
113
-			// Found us, get children entries
114
-			var ls git.Entries
115
-			if ls, err = tree.ListEntries(); err != nil {
116
-				return nil, err
117
-			}
118
-			// Call itself recursively to find needed entry
119
-			var te *git.TreeEntry
120
-			if te, err = commitTreeDirEntry(repo, commit, ls, path, targets, textOnly); err != nil {
121
-				return nil, err
122
-			}
123
-			if te != nil {
124
-				return te, nil
125
-			}
126
-		}
127
-	}
128
-	return nil, nil
129
-}
130
-
131
-// commitTreeEntry is a first step of commitTreeDirEntry, which should be never called directly
132
-func commitTreeEntry(repo *git.Repository, commit *git.Commit, targets []string, textOnly bool) (*git.TreeEntry, error) {
53
+// findEntryForFile finds the tree entry for a target filepath.
54
+func findEntryForFile(commit *git.Commit, target string) (*git.TreeEntry, error) {
133 55
 	entries, err := commit.ListEntries()
134 56
 	if err != nil {
135 57
 		return nil, err
136 58
 	}
137
-	return commitTreeDirEntry(repo, commit, entries, "", targets, textOnly)
138
-}
139
-
140
-// findFile finds the best match for given filename in repo file tree
141
-func findFile(repo *git.Repository, commit *git.Commit, target string, textOnly bool) (*git.TreeEntry, error) {
142
-	targets := []string{target, urlEncoded(target), urlDecoded(target)}
143
-	var entry *git.TreeEntry
144
-	var err error
145
-	if entry, err = commitTreeEntry(repo, commit, targets, textOnly); err != nil {
146
-		return nil, err
147
-	}
148
-	return entry, nil
149
-}
150
-
151
-// matchName matches generic name representation of the file with required one
152
-func matchName(target, name string) bool {
153
-	if len(target) != len(name) {
154
-		return false
155
-	}
156
-	name = strings.ToLower(name)
157
-	target = strings.ToLower(target)
158
-	if name == target {
159
-		return true
160
-	}
161
-	target = strings.Replace(target, " ", "?", -1)
162
-	target = strings.Replace(target, "-", "?", -1)
163
-	for i := range name {
164
-		ch := name[i]
165
-		reqCh := target[i]
166
-		if ch != reqCh {
167
-			if string(reqCh) != "?" {
168
-				return false
169
-			}
59
+	for _, entry := range entries {
60
+		if entry.Type == git.ObjectBlob && entry.Name() == target {
61
+			return entry, nil
170 62
 		}
171 63
 	}
172
-	return true
64
+	return nil, nil
173 65
 }
174 66
 
175 67
 func findWikiRepoCommit(ctx *context.Context) (*git.Repository, *git.Commit, error) {
176 68
 	wikiRepo, err := git.OpenRepository(ctx.Repo.Repository.WikiPath())
177 69
 	if err != nil {
178
-		// ctx.Handle(500, "OpenRepository", err)
70
+		ctx.Handle(500, "OpenRepository", err)
179 71
 		return nil, nil, err
180 72
 	}
181
-	if !wikiRepo.IsBranchExist("master") {
182
-		return wikiRepo, nil, nil
183
-	}
184 73
 
185 74
 	commit, err := wikiRepo.GetBranchCommit("master")
186 75
 	if err != nil {
@@ -190,14 +79,40 @@ func findWikiRepoCommit(ctx *context.Context) (*git.Repository, *git.Commit, err
190 79
 	return wikiRepo, commit, nil
191 80
 }
192 81
 
82
+// wikiContentsByEntry returns the contents of the wiki page referenced by the
83
+// given tree entry. Writes to ctx if an error occurs.
84
+func wikiContentsByEntry(ctx *context.Context, entry *git.TreeEntry) []byte {
85
+	reader, err := entry.Blob().Data()
86
+	if err != nil {
87
+		ctx.Handle(500, "Blob.Data", err)
88
+		return nil
89
+	}
90
+	content, err := ioutil.ReadAll(reader)
91
+	if err != nil {
92
+		ctx.Handle(500, "ReadAll", err)
93
+		return nil
94
+	}
95
+	return content
96
+}
97
+
98
+// wikiContentsByName returns the contents of a wiki page, along with a boolean
99
+// indicating whether the page exists. Writes to ctx if an error occurs.
100
+func wikiContentsByName(ctx *context.Context, commit *git.Commit, wikiName string) ([]byte, bool) {
101
+	entry, err := findEntryForFile(commit, models.WikiNameToFilename(wikiName))
102
+	if err != nil {
103
+		ctx.Handle(500, "findEntryForFile", err)
104
+		return nil, false
105
+	} else if entry == nil {
106
+		return nil, false
107
+	}
108
+	return wikiContentsByEntry(ctx, entry), true
109
+}
110
+
193 111
 func renderWikiPage(ctx *context.Context, isViewPage bool) (*git.Repository, *git.TreeEntry) {
194 112
 	wikiRepo, commit, err := findWikiRepoCommit(ctx)
195 113
 	if err != nil {
196 114
 		return nil, nil
197 115
 	}
198
-	if commit == nil {
199
-		return wikiRepo, nil
200
-	}
201 116
 
202 117
 	// Get page list.
203 118
 	if isViewPage {
@@ -206,85 +121,62 @@ func renderWikiPage(ctx *context.Context, isViewPage bool) (*git.Repository, *gi
206 121
 			ctx.Handle(500, "ListEntries", err)
207 122
 			return nil, nil
208 123
 		}
209
-		pages := []PageMeta{}
210
-		for i := range entries {
211
-			if entries[i].Type == git.ObjectBlob {
212
-				name := entries[i].Name()
213
-				ext := filepath.Ext(name)
214
-				if markdown.IsMarkdownFile(name) || ext == ".textile" {
215
-					name = strings.TrimSuffix(name, ext)
216
-					if name == "" || name == "_Sidebar" || name == "_Footer" || name == "_Header" {
217
-						continue
218
-					}
219
-					pages = append(pages, PageMeta{
220
-						Name: models.ToWikiPageName(name),
221
-						URL:  name,
222
-					})
223
-				}
124
+		pages := make([]PageMeta, 0, len(entries))
125
+		for _, entry := range entries {
126
+			if entry.Type != git.ObjectBlob {
127
+				continue
224 128
 			}
129
+			wikiName, err := models.WikiFilenameToName(entry.Name())
130
+			if err != nil {
131
+				ctx.Handle(500, "WikiFilenameToName", err)
132
+				return nil, nil
133
+			} else if wikiName == "_Sidebar" || wikiName == "_Footer" {
134
+				continue
135
+			}
136
+			pages = append(pages, PageMeta{
137
+				Name:   wikiName,
138
+				SubURL: models.WikiNameToSubURL(wikiName),
139
+			})
225 140
 		}
226 141
 		ctx.Data["Pages"] = pages
227 142
 	}
228 143
 
229
-	pageURL := ctx.Params(":page")
230
-	if len(pageURL) == 0 {
231
-		pageURL = "Home"
144
+	pageName := models.NormalizeWikiName(ctx.Params(":page"))
145
+	if len(pageName) == 0 {
146
+		pageName = "Home"
232 147
 	}
233
-	ctx.Data["PageURL"] = pageURL
148
+	ctx.Data["PageURL"] = models.WikiNameToSubURL(pageName)
234 149
 
235
-	pageName := models.ToWikiPageName(pageURL)
236 150
 	ctx.Data["old_title"] = pageName
237 151
 	ctx.Data["Title"] = pageName
238 152
 	ctx.Data["title"] = pageName
239 153
 	ctx.Data["RequireHighlightJS"] = true
240 154
 
155
+	pageFilename := models.WikiNameToFilename(pageName)
241 156
 	var entry *git.TreeEntry
242
-	if entry, err = findFile(wikiRepo, commit, pageName, true); err != nil {
243
-		ctx.Handle(500, "findFile", err)
157
+	if entry, err = findEntryForFile(commit, pageFilename); err != nil {
158
+		ctx.Handle(500, "findEntryForFile", err)
244 159
 		return nil, nil
245
-	}
246
-	if entry == nil {
160
+	} else if entry == nil {
247 161
 		ctx.Redirect(ctx.Repo.RepoLink + "/wiki/_pages")
248 162
 		return nil, nil
249 163
 	}
250
-	blob := entry.Blob()
251
-	r, err := blob.Data()
252
-	if err != nil {
253
-		ctx.Handle(500, "Data", err)
254
-		return nil, nil
255
-	}
256
-	data, err := ioutil.ReadAll(r)
257
-	if err != nil {
258
-		ctx.Handle(500, "ReadAll", err)
164
+	data := wikiContentsByEntry(ctx, entry)
165
+	if ctx.Written() {
259 166
 		return nil, nil
260 167
 	}
261
-	sidebarPresent := false
262
-	sidebarContent := []byte{}
263
-	sentry, err := findFile(wikiRepo, commit, "_Sidebar", true)
264
-	if err == nil && sentry != nil {
265
-		r, err = sentry.Blob().Data()
266
-		if err == nil {
267
-			dataSB, err := ioutil.ReadAll(r)
268
-			if err == nil {
269
-				sidebarPresent = true
270
-				sidebarContent = dataSB
271
-			}
168
+
169
+	if isViewPage {
170
+		sidebarContent, sidebarPresent := wikiContentsByName(ctx, commit, "_Sidebar")
171
+		if ctx.Written() {
172
+			return nil, nil
272 173
 		}
273
-	}
274
-	footerPresent := false
275
-	footerContent := []byte{}
276
-	sentry, err = findFile(wikiRepo, commit, "_Footer", true)
277
-	if err == nil && sentry != nil {
278
-		r, err = sentry.Blob().Data()
279
-		if err == nil {
280
-			dataSB, err := ioutil.ReadAll(r)
281
-			if err == nil {
282
-				footerPresent = true
283
-				footerContent = dataSB
284
-			}
174
+
175
+		footerContent, footerPresent := wikiContentsByName(ctx, commit, "_Footer")
176
+		if ctx.Written() {
177
+			return nil, nil
285 178
 		}
286
-	}
287
-	if isViewPage {
179
+
288 180
 		metas := ctx.Repo.Repository.ComposeMetas()
289 181
 		ctx.Data["content"] = markdown.RenderWiki(data, ctx.Repo.RepoLink, metas)
290 182
 		ctx.Data["sidebarPresent"] = sidebarPresent
@@ -322,13 +214,13 @@ func Wiki(ctx *context.Context) {
322 214
 		return
323 215
 	}
324 216
 
325
-	ename := entry.Name()
326
-	if markup.Type(ename) != markdown.MarkupName {
327
-		ext := strings.ToUpper(filepath.Ext(ename))
217
+	wikiPath := entry.Name()
218
+	if markup.Type(wikiPath) != markdown.MarkupName {
219
+		ext := strings.ToUpper(filepath.Ext(wikiPath))
328 220
 		ctx.Data["FormatWarning"] = fmt.Sprintf("%s rendering is not supported at the moment. Rendered as Markdown.", ext)
329 221
 	}
330 222
 	// Get last change information.
331
-	lastCommit, err := wikiRepo.GetCommitByPath(ename)
223
+	lastCommit, err := wikiRepo.GetCommitByPath(wikiPath)
332 224
 	if err != nil {
333 225
 		ctx.Handle(500, "GetCommitByPath", err)
334 226
 		return
@@ -359,27 +251,25 @@ func WikiPages(ctx *context.Context) {
359 251
 		return
360 252
 	}
361 253
 	pages := make([]PageMeta, 0, len(entries))
362
-	for i := range entries {
363
-		if entries[i].Type == git.ObjectBlob {
364
-			c, err := wikiRepo.GetCommitByPath(entries[i].Name())
365
-			if err != nil {
366
-				ctx.Handle(500, "GetCommit", err)
367
-				return
368
-			}
369
-			name := entries[i].Name()
370
-			ext := filepath.Ext(name)
371
-			if markdown.IsMarkdownFile(name) || ext == ".textile" {
372
-				name = strings.TrimSuffix(name, ext)
373
-				if name == "" {
374
-					continue
375
-				}
376
-				pages = append(pages, PageMeta{
377
-					Name:    models.ToWikiPageName(name),
378
-					URL:     name,
379
-					Updated: c.Author.When,
380
-				})
381
-			}
254
+	for _, entry := range entries {
255
+		if entry.Type != git.ObjectBlob {
256
+			continue
257
+		}
258
+		c, err := wikiRepo.GetCommitByPath(entry.Name())
259
+		if err != nil {
260
+			ctx.Handle(500, "GetCommit", err)
261
+			return
262
+		}
263
+		wikiName, err := models.WikiFilenameToName(entry.Name())
264
+		if err != nil {
265
+			ctx.Handle(500, "WikiFilenameToName", err)
266
+			return
382 267
 		}
268
+		pages = append(pages, PageMeta{
269
+			Name:    wikiName,
270
+			SubURL:  models.WikiNameToSubURL(wikiName),
271
+			Updated: c.Author.When,
272
+		})
383 273
 	}
384 274
 	ctx.Data["Pages"] = pages
385 275
 
@@ -394,31 +284,23 @@ func WikiRaw(ctx *context.Context) {
394 284
 			return
395 285
 		}
396 286
 	}
397
-	uri := ctx.Params("*")
287
+	providedPath := ctx.Params("*")
288
+	if strings.HasSuffix(providedPath, ".md") {
289
+		providedPath = providedPath[:len(providedPath)-3]
290
+	}
291
+	wikiPath := models.WikiNameToFilename(providedPath)
398 292
 	var entry *git.TreeEntry
399 293
 	if commit != nil {
400
-		entry, err = findFile(wikiRepo, commit, uri, false)
401
-	}
402
-	if err != nil || entry == nil {
403
-		if entry == nil || commit == nil {
404
-			defBranch := ctx.Repo.Repository.DefaultBranch
405
-			if commit, err = ctx.Repo.GitRepo.GetBranchCommit(defBranch); commit == nil || err != nil {
406
-				ctx.Handle(500, "GetBranchCommit", err)
407
-				return
408
-			}
409
-			if entry, err = findFile(ctx.Repo.GitRepo, commit, uri, false); err != nil {
410
-				ctx.Handle(500, "findFile", err)
411
-				return
412
-			}
413
-			if entry == nil {
414
-				ctx.Handle(404, "findFile", nil)
415
-				return
416
-			}
417
-		} else {
418
-			ctx.Handle(500, "findFile", err)
419
-			return
420
-		}
294
+		entry, err = findEntryForFile(commit, wikiPath)
421 295
 	}
296
+	if err != nil {
297
+		ctx.Handle(500, "findFile", err)
298
+		return
299
+	} else if entry == nil {
300
+		ctx.Handle(404, "findEntryForFile", nil)
301
+		return
302
+	}
303
+
422 304
 	if err = ServeBlob(ctx, entry.Blob()); err != nil {
423 305
 		ctx.Handle(500, "ServeBlob", err)
424 306
 	}
@@ -437,7 +319,7 @@ func NewWiki(ctx *context.Context) {
437 319
 	ctx.HTML(200, tplWikiNew)
438 320
 }
439 321
 
440
-// NewWikiPost response fro wiki create request
322
+// NewWikiPost response for wiki create request
441 323
 func NewWikiPost(ctx *context.Context, form auth.NewWikiForm) {
442 324
 	ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page")
443 325
 	ctx.Data["PageIsWiki"] = true
@@ -448,10 +330,12 @@ func NewWikiPost(ctx *context.Context, form auth.NewWikiForm) {
448 330
 		return
449 331
 	}
450 332
 
451
-	wikiPath := models.ToWikiPageURL(form.Title)
452
-
453
-	if err := ctx.Repo.Repository.AddWikiPage(ctx.User, wikiPath, form.Content, form.Message); err != nil {
454
-		if models.IsErrWikiAlreadyExist(err) {
333
+	wikiName := models.NormalizeWikiName(form.Title)
334
+	if err := ctx.Repo.Repository.AddWikiPage(ctx.User, wikiName, form.Content, form.Message); err != nil {
335
+		if models.IsErrWikiReservedName(err) {
336
+			ctx.Data["Err_Title"] = true
337
+			ctx.RenderWithErr(ctx.Tr("repo.wiki.reserved_page", wikiName), tplWikiNew, &form)
338
+		} else if models.IsErrWikiAlreadyExist(err) {
455 339
 			ctx.Data["Err_Title"] = true
456 340
 			ctx.RenderWithErr(ctx.Tr("repo.wiki.page_already_exists"), tplWikiNew, &form)
457 341
 		} else {
@@ -460,7 +344,7 @@ func NewWikiPost(ctx *context.Context, form auth.NewWikiForm) {
460 344
 		return
461 345
 	}
462 346
 
463
-	ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + wikiPath)
347
+	ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + models.WikiNameToFilename(wikiName))
464 348
 }
465 349
 
466 350
 // EditWiki render wiki modify page
@@ -482,7 +366,7 @@ func EditWiki(ctx *context.Context) {
482 366
 	ctx.HTML(200, tplWikiNew)
483 367
 }
484 368
 
485
-// EditWikiPost response fro wiki modify request
369
+// EditWikiPost response for wiki modify request
486 370
 func EditWikiPost(ctx *context.Context, form auth.NewWikiForm) {
487 371
 	ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page")
488 372
 	ctx.Data["PageIsWiki"] = true
@@ -493,25 +377,25 @@ func EditWikiPost(ctx *context.Context, form auth.NewWikiForm) {
493 377
 		return
494 378
 	}
495 379
 
496
-	oldWikiPath := models.ToWikiPageURL(ctx.Params(":page"))
497
-	newWikiPath := models.ToWikiPageURL(form.Title)
380
+	oldWikiName := models.NormalizeWikiName(ctx.Params(":page"))
381
+	newWikiName := models.NormalizeWikiName(form.Title)
498 382
 
499
-	if err := ctx.Repo.Repository.EditWikiPage(ctx.User, oldWikiPath, newWikiPath, form.Content, form.Message); err != nil {
383
+	if err := ctx.Repo.Repository.EditWikiPage(ctx.User, oldWikiName, newWikiName, form.Content, form.Message); err != nil {
500 384
 		ctx.Handle(500, "EditWikiPage", err)
501 385
 		return
502 386
 	}
503 387
 
504
-	ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + newWikiPath)
388
+	ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + models.WikiNameToFilename(newWikiName))
505 389
 }
506 390
 
507 391
 // DeleteWikiPagePost delete wiki page
508 392
 func DeleteWikiPagePost(ctx *context.Context) {
509
-	pageURL := models.ToWikiPageURL(ctx.Params(":page"))
510
-	if len(pageURL) == 0 {
511
-		pageURL = "Home"
393
+	wikiName := models.NormalizeWikiName(ctx.Params(":page"))
394
+	if len(wikiName) == 0 {
395
+		wikiName = "Home"
512 396
 	}
513 397
 
514
-	if err := ctx.Repo.Repository.DeleteWikiPage(ctx.User, pageURL); err != nil {
398
+	if err := ctx.Repo.Repository.DeleteWikiPage(ctx.User, wikiName); err != nil {
515 399
 		ctx.Handle(500, "DeleteWikiPage", err)
516 400
 		return
517 401
 	}

+ 0 - 1
routers/routes/routes.go

@@ -608,7 +608,6 @@ func RegisterRoutes(m *macaron.Macaron) {
608 608
 
609 609
 		m.Group("/wiki", func() {
610 610
 			m.Get("/raw/*", repo.WikiRaw)
611
-			m.Get("/*", repo.WikiRaw)
612 611
 		}, repo.MustEnableWiki)
613 612
 
614 613
 		m.Group("/activity", func() {

+ 1 - 1
templates/repo/wiki/pages.tmpl

@@ -16,7 +16,7 @@
16 16
 					<tr>
17 17
 						<td>
18 18
 							<i class="octicon octicon-file-text"></i>
19
-							<a href="{{$.RepoLink}}/wiki/{{.URL}}">{{.Name}}</a>
19
+							<a href="{{$.RepoLink}}/wiki/{{.SubURL}}">{{.Name}}</a>
20 20
 						</td>
21 21
 						{{$timeSince := TimeSince .Updated $.Lang}}
22 22
 						<td class="text right grey">{{$.i18n.Tr "repo.wiki.last_updated" $timeSince | Safe}}</td>

+ 4 - 4
templates/repo/wiki/view.tmpl

@@ -21,7 +21,7 @@
21 21
 							</div>
22 22
 							<div class="scrolling menu">
23 23
 								{{range .Pages}}
24
-									<div class="item {{if eq $.Title .Name}}selected{{end}}" data-url="{{$.RepoLink}}/wiki/{{.URL}}">{{.Name}}</div>
24
+									<div class="item {{if eq $.Title .Name}}selected{{end}}" data-url="{{$.RepoLink}}/wiki/{{.SubURL}}">{{.Name}}</div>
25 25
 								{{end}}
26 26
 							</div>
27 27
 						</div>
@@ -57,9 +57,9 @@
57 57
 			{{$title}}
58 58
 			{{if and .IsRepositoryWriter (not .Repository.IsMirror)}}
59 59
 				<div class="ui right">
60
-					<a class="ui small button" href="{{.RepoLink}}/wiki/{{EscapePound .PageURL}}/_edit">{{.i18n.Tr "repo.wiki.edit_page_button"}}</a>
60
+					<a class="ui small button" href="{{.RepoLink}}/wiki/{{.PageURL}}/_edit">{{.i18n.Tr "repo.wiki.edit_page_button"}}</a>
61 61
 					<a class="ui green small button" href="{{.RepoLink}}/wiki/_new">{{.i18n.Tr "repo.wiki.new_page_button"}}</a>
62
-					<a class="ui red small button delete-button" href="" data-url="{{.RepoLink}}/wiki/{{EscapePound .PageURL}}/delete" data-id="{{EscapePound .PageURL}}">{{.i18n.Tr "repo.wiki.delete_page_button"}}</a>
62
+					<a class="ui red small button delete-button" href="" data-url="{{.RepoLink}}/wiki/{{.PageURL}}/delete" data-id="{{.PageURL}}">{{.i18n.Tr "repo.wiki.delete_page_button"}}</a>
63 63
 				</div>
64 64
 			{{end}}
65 65
 			<div class="ui sub header">
@@ -85,7 +85,7 @@
85 85
 			{{end}}
86 86
 		</div>
87 87
 		{{if .footerPresent}}
88
-		<div class="ui grey segment">
88
+		<div class="ui segment">
89 89
 			{{.footerContent | Str2html}}
90 90
 		</div>
91 91
 		{{end}}

+ 10 - 0
vendor/github.com/Unknwon/com/convert.go

@@ -41,6 +41,11 @@ func (f StrTo) Int64() (int64, error) {
41 41
 	return int64(v), err
42 42
 }
43 43
 
44
+func (f StrTo) Float64() (float64, error) {
45
+	v, err := strconv.ParseFloat(f.String(), 64)
46
+	return float64(v), err
47
+}
48
+
44 49
 func (f StrTo) MustUint8() uint8 {
45 50
 	v, _ := f.Uint8()
46 51
 	return v
@@ -56,6 +61,11 @@ func (f StrTo) MustInt64() int64 {
56 61
 	return v
57 62
 }
58 63
 
64
+func (f StrTo) MustFloat64() float64 {
65
+	v, _ := f.Float64()
66
+	return v
67
+}
68
+
59 69
 func (f StrTo) String() string {
60 70
 	if f.Exist() {
61 71
 		return string(f)

+ 31 - 21
vendor/github.com/Unknwon/com/string.go

@@ -19,9 +19,7 @@ import (
19 19
 	"crypto/aes"
20 20
 	"crypto/cipher"
21 21
 	"crypto/rand"
22
-	"encoding/base64"
23 22
 	"errors"
24
-	"io"
25 23
 	r "math/rand"
26 24
 	"strconv"
27 25
 	"strings"
@@ -30,41 +28,53 @@ import (
30 28
 	"unicode/utf8"
31 29
 )
32 30
 
33
-// AESEncrypt encrypts text and given key with AES.
34
-func AESEncrypt(key, text []byte) ([]byte, error) {
31
+// AESGCMEncrypt encrypts plaintext with the given key using AES in GCM mode.
32
+func AESGCMEncrypt(key, plaintext []byte) ([]byte, error) {
35 33
 	block, err := aes.NewCipher(key)
36 34
 	if err != nil {
37 35
 		return nil, err
38 36
 	}
39
-	b := base64.StdEncoding.EncodeToString(text)
40
-	ciphertext := make([]byte, aes.BlockSize+len(b))
41
-	iv := ciphertext[:aes.BlockSize]
42
-	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
37
+
38
+	gcm, err := cipher.NewGCM(block)
39
+	if err != nil {
43 40
 		return nil, err
44 41
 	}
45
-	cfb := cipher.NewCFBEncrypter(block, iv)
46
-	cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
47
-	return ciphertext, nil
42
+
43
+	nonce := make([]byte, gcm.NonceSize())
44
+	if _, err := rand.Read(nonce); err != nil {
45
+		return nil, err
46
+	}
47
+
48
+	ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
49
+	return append(nonce, ciphertext...), nil
48 50
 }
49 51
 
50
-// AESDecrypt decrypts text and given key with AES.
51
-func AESDecrypt(key, text []byte) ([]byte, error) {
52
+// AESGCMDecrypt decrypts ciphertext with the given key using AES in GCM mode.
53
+func AESGCMDecrypt(key, ciphertext []byte) ([]byte, error) {
52 54
 	block, err := aes.NewCipher(key)
53 55
 	if err != nil {
54 56
 		return nil, err
55 57
 	}
56
-	if len(text) < aes.BlockSize {
57
-		return nil, errors.New("ciphertext too short")
58
+
59
+	gcm, err := cipher.NewGCM(block)
60
+	if err != nil {
61
+		return nil, err
62
+	}
63
+
64
+	size := gcm.NonceSize()
65
+	if len(ciphertext)-size <= 0 {
66
+		return nil, errors.New("Ciphertext is empty")
58 67
 	}
59
-	iv := text[:aes.BlockSize]
60
-	text = text[aes.BlockSize:]
61
-	cfb := cipher.NewCFBDecrypter(block, iv)
62
-	cfb.XORKeyStream(text, text)
63
-	data, err := base64.StdEncoding.DecodeString(string(text))
68
+
69
+	nonce := ciphertext[:size]
70
+	ciphertext = ciphertext[size:]
71
+
72
+	plainText, err := gcm.Open(nil, nonce, ciphertext, nil)
64 73
 	if err != nil {
65 74
 		return nil, err
66 75
 	}
67
-	return data, nil
76
+
77
+	return plainText, nil
68 78
 }
69 79
 
70 80
 // IsLetter returns true if the 'l' is an English letter.

+ 1 - 1
vendor/gopkg.in/macaron.v1/LICENSE

@@ -176,7 +176,7 @@ recommend that a file or class name and description of purpose be included on
176 176
 the same "printed page" as the copyright notice for easier identification within
177 177
 third-party archives.
178 178
 
179
-   Copyright [yyyy] [name of copyright owner]
179
+   Copyright 2014 The Macaron Authors
180 180
 
181 181
    Licensed under the Apache License, Version 2.0 (the "License");
182 182
    you may not use this file except in compliance with the License.

+ 4 - 3
vendor/gopkg.in/macaron.v1/README.md

@@ -1,4 +1,4 @@
1
-Macaron [![Build Status](https://travis-ci.org/go-macaron/macaron.svg?branch=v1)](https://travis-ci.org/go-macaron/macaron) [![](http://gocover.io/_badge/github.com/go-macaron/macaron)](http://gocover.io/github.com/go-macaron/macaron)
1
+Macaron [![Build Status](https://travis-ci.org/go-macaron/macaron.svg?branch=v1)](https://travis-ci.org/go-macaron/macaron)
2 2
 =======================
3 3
 
4 4
 ![Macaron Logo](https://raw.githubusercontent.com/go-macaron/macaron/v1/macaronlogo.png)
@@ -61,18 +61,20 @@ There are already many [middlewares](https://github.com/go-macaron) to simplify
61 61
 - [bindata](https://github.com/go-macaron/bindata) - Embed binary data as static and template files
62 62
 - [toolbox](https://github.com/go-macaron/toolbox) - Health check, pprof, profile and statistic services
63 63
 - [oauth2](https://github.com/go-macaron/oauth2) - OAuth 2.0 backend
64
+- [authz](https://github.com/go-macaron/authz) - ACL/RBAC/ABAC authorization based on Casbin
64 65
 - [switcher](https://github.com/go-macaron/switcher) - Multiple-site support
65 66
 - [method](https://github.com/go-macaron/method) - HTTP method override
66 67
 - [permissions2](https://github.com/xyproto/permissions2) - Cookies, users and permissions
67 68
 - [renders](https://github.com/go-macaron/renders) - Beego-like render engine(Macaron has built-in template engine, this is another option)
69
+- [piwik](https://github.com/veecue/piwik-middleware) - Server-side piwik analytics
68 70
 
69 71
 ## Use Cases
70 72
 
71 73
 - [Gogs](https://gogs.io): A painless self-hosted Git Service
74
+- [Grafana](http://grafana.org/): The open platform for beautiful analytics and monitoring
72 75
 - [Peach](https://peachdocs.org): A modern web documentation server
73 76
 - [Go Walker](https://gowalker.org): Go online API documentation
74 77
 - [Switch](https://gopm.io): Gopm registry
75
-- [YouGam](http://yougam.com): Online Forum
76 78
 - [Critical Stack Intel](https://intel.criticalstack.com/): A 100% free intel marketplace from Critical Stack, Inc.
77 79
 
78 80
 ## Getting Help
@@ -80,7 +82,6 @@ There are already many [middlewares](https://github.com/go-macaron) to simplify
80 82
 - [API Reference](https://gowalker.org/gopkg.in/macaron.v1)
81 83
 - [Documentation](https://go-macaron.com)
82 84
 - [FAQs](https://go-macaron.com/docs/faqs)
83
-- [![Join the chat at https://gitter.im/Unknwon/macaron](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-macaron/macaron?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
84 85
 
85 86
 ## Credits
86 87
 

+ 23 - 11
vendor/gopkg.in/macaron.v1/context.go

@@ -15,7 +15,7 @@
15 15
 package macaron
16 16
 
17 17
 import (
18
-	"crypto/md5"
18
+	"crypto/sha256"
19 19
 	"encoding/hex"
20 20
 	"html/template"
21 21
 	"io"
@@ -32,8 +32,8 @@ import (
32 32
 	"time"
33 33
 
34 34
 	"github.com/Unknwon/com"
35
-
36 35
 	"github.com/go-macaron/inject"
36
+	"golang.org/x/crypto/pbkdf2"
37 37
 )
38 38
 
39 39
 // Locale reprents a localization interface.
@@ -72,6 +72,14 @@ func (r *Request) Body() *RequestBody {
72 72
 	return &RequestBody{r.Request.Body}
73 73
 }
74 74
 
75
+// ContextInvoker is an inject.FastInvoker wrapper of func(ctx *Context).
76
+type ContextInvoker func(ctx *Context)
77
+
78
+func (invoke ContextInvoker) Invoke(params []interface{}) ([]reflect.Value, error) {
79
+	invoke(params[0].(*Context))
80
+	return nil, nil
81
+}
82
+
75 83
 // Context represents the runtime context of current request of Macaron instance.
76 84
 // It is the integration of most frequently used middlewares and helper methods.
77 85
 type Context struct {
@@ -260,6 +268,11 @@ func (ctx *Context) SetParams(name, val string) {
260 268
 	ctx.params[name] = val
261 269
 }
262 270
 
271
+// ReplaceAllParams replace all current params with given params
272
+func (ctx *Context) ReplaceAllParams(params Params) {
273
+	ctx.params = params;
274
+}
275
+
263 276
 // ParamsEscape returns escapred params result.
264 277
 // e.g. ctx.ParamsEscape(":uname")
265 278
 func (ctx *Context) ParamsEscape(name string) string {
@@ -411,30 +424,29 @@ func (ctx *Context) GetSecureCookie(key string) (string, bool) {
411 424
 
412 425
 // SetSuperSecureCookie sets given cookie value to response header with secret string.
413 426
 func (ctx *Context) SetSuperSecureCookie(secret, name, value string, others ...interface{}) {
414
-	m := md5.Sum([]byte(secret))
415
-	secret = hex.EncodeToString(m[:])
416
-	text, err := com.AESEncrypt([]byte(secret), []byte(value))
427
+	key := pbkdf2.Key([]byte(secret), []byte(secret), 1000, 16, sha256.New)
428
+	text, err := com.AESGCMEncrypt(key, []byte(value))
417 429
 	if err != nil {
418 430
 		panic("error encrypting cookie: " + err.Error())
419 431
 	}
432
+
420 433
 	ctx.SetCookie(name, hex.EncodeToString(text), others...)
421 434
 }
422 435
 
423 436
 // GetSuperSecureCookie returns given cookie value from request header with secret string.
424
-func (ctx *Context) GetSuperSecureCookie(secret, key string) (string, bool) {
425
-	val := ctx.GetCookie(key)
437
+func (ctx *Context) GetSuperSecureCookie(secret, name string) (string, bool) {
438
+	val := ctx.GetCookie(name)
426 439
 	if val == "" {
427 440
 		return "", false
428 441
 	}
429 442
 
430
-	data, err := hex.DecodeString(val)
443
+	text, err := hex.DecodeString(val)
431 444
 	if err != nil {
432 445
 		return "", false
433 446
 	}
434 447
 
435
-	m := md5.Sum([]byte(secret))
436
-	secret = hex.EncodeToString(m[:])
437
-	text, err := com.AESDecrypt([]byte(secret), data)
448
+	key := pbkdf2.Key([]byte(secret), []byte(secret), 1000, 16, sha256.New)
449
+	text, err = com.AESGCMDecrypt(key, text)
438 450
 	return string(text), err == nil
439 451
 }
440 452
 

+ 10 - 1
vendor/gopkg.in/macaron.v1/logger.go

@@ -19,6 +19,7 @@ import (
19 19
 	"fmt"
20 20
 	"log"
21 21
 	"net/http"
22
+	"reflect"
22 23
 	"runtime"
23 24
 	"time"
24 25
 )
@@ -32,6 +33,14 @@ func init() {
32 33
 	ColorLog = runtime.GOOS != "windows"
33 34
 }
34 35
 
36
+// LoggerInvoker is an inject.FastInvoker wrapper of func(ctx *Context, log *log.Logger).
37
+type LoggerInvoker func(ctx *Context, log *log.Logger)
38
+
39
+func (invoke LoggerInvoker) Invoke(params []interface{}) ([]reflect.Value, error) {
40
+	invoke(params[0].(*Context), params[1].(*log.Logger))
41
+	return nil, nil
42
+}
43
+
35 44
 // Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
36 45
 func Logger() Handler {
37 46
 	return func(ctx *Context, log *log.Logger) {
@@ -42,7 +51,7 @@ func Logger() Handler {
42 51
 		rw := ctx.Resp.(ResponseWriter)
43 52
 		ctx.Next()
44 53
 
45
-		content := fmt.Sprintf("%s: Completed %s %v %s in %v", time.Now().Format(LogTimeFormat), ctx.Req.RequestURI, rw.Status(), http.StatusText(rw.Status()), time.Since(start))
54
+		content := fmt.Sprintf("%s: Completed %s %s %v %s in %v", time.Now().Format(LogTimeFormat), ctx.Req.Method, ctx.Req.RequestURI, rw.Status(), http.StatusText(rw.Status()), time.Since(start))
46 55
 		if ColorLog {
47 56
 			switch rw.Status() {
48 57
 			case 200, 201, 202:

+ 55 - 12
vendor/gopkg.in/macaron.v1/macaron.go

@@ -32,7 +32,7 @@ import (
32 32
 	"github.com/go-macaron/inject"
33 33
 )
34 34
 
35
-const _VERSION = "1.1.12.0122"
35
+const _VERSION = "1.2.4.1123"
36 36
 
37 37
 func Version() string {
38 38
 	return _VERSION
@@ -43,20 +43,63 @@ func Version() string {
43 43
 // and panics if an argument could not be fullfilled via dependency injection.
44 44
 type Handler interface{}
45 45
 
46
-// validateHandler makes sure a handler is a callable function,
47
-// and panics if it is not.
48
-func validateHandler(h Handler) {
46
+// handlerFuncInvoker is an inject.FastInvoker wrapper of func(http.ResponseWriter, *http.Request).
47
+type handlerFuncInvoker func(http.ResponseWriter, *http.Request)
48
+
49
+func (invoke handlerFuncInvoker) Invoke(params []interface{}) ([]reflect.Value, error) {
50
+	invoke(params[0].(http.ResponseWriter), params[1].(*http.Request))
51
+	return nil, nil
52
+}
53
+
54
+// internalServerErrorInvoker is an inject.FastInvoker wrapper of func(rw http.ResponseWriter, err error).
55
+type internalServerErrorInvoker func(rw http.ResponseWriter, err error)
56
+
57
+func (invoke internalServerErrorInvoker) Invoke(params []interface{}) ([]reflect.Value, error) {
58
+	invoke(params[0].(http.ResponseWriter), params[1].(error))
59
+	return nil, nil
60
+}
61
+
62
+// validateAndWrapHandler makes sure a handler is a callable function, it panics if not.
63
+// When the handler is also potential to be any built-in inject.FastInvoker,
64
+// it wraps the handler automatically to have some performance gain.
65
+func validateAndWrapHandler(h Handler) Handler {
49 66
 	if reflect.TypeOf(h).Kind() != reflect.Func {
50 67
 		panic("Macaron handler must be a callable function")
51 68
 	}
69
+
70
+	if !inject.IsFastInvoker(h) {
71
+		switch v := h.(type) {
72
+		case func(*Context):
73
+			return ContextInvoker(v)
74
+		case func(*Context, *log.Logger):
75
+			return LoggerInvoker(v)
76
+		case func(http.ResponseWriter, *http.Request):
77
+			return handlerFuncInvoker(v)
78
+		case func(http.ResponseWriter, error):
79
+			return internalServerErrorInvoker(v)
80
+		}
81
+	}
82
+	return h
52 83
 }
53 84
 
54
-// validateHandlers makes sure handlers are callable functions,
55
-// and panics if any of them is not.
56
-func validateHandlers(handlers []Handler) {
57
-	for _, h := range handlers {
58
-		validateHandler(h)
85
+// validateAndWrapHandlers preforms validation and wrapping for each input handler.
86
+// It accepts an optional wrapper function to perform custom wrapping on handlers.
87
+func validateAndWrapHandlers(handlers []Handler, wrappers ...func(Handler) Handler) []Handler {
88
+	var wrapper func(Handler) Handler
89
+	if len(wrappers) > 0 {
90
+		wrapper = wrappers[0]
91
+	}
92
+
93
+	wrappedHandlers := make([]Handler, len(handlers))
94
+	for i, h := range handlers {
95
+		h = validateAndWrapHandler(h)
96
+		if wrapper != nil && !inject.IsFastInvoker(h) {
97
+			h = wrapper(h)
98
+		}
99
+		wrappedHandlers[i] = h
59 100
 	}
101
+
102
+	return wrappedHandlers
60 103
 }
61 104
 
62 105
 // Macaron represents the top level web application.
@@ -101,7 +144,7 @@ func New() *Macaron {
101 144
 }
102 145
 
103 146
 // Classic creates a classic Macaron with some basic default middleware:
104
-// mocaron.Logger, mocaron.Recovery and mocaron.Static.
147
+// macaron.Logger, macaron.Recovery and macaron.Static.
105 148
 func Classic() *Macaron {
106 149
 	m := New()
107 150
 	m.Use(Logger())
@@ -123,7 +166,7 @@ func (m *Macaron) Handlers(handlers ...Handler) {
123 166
 // Action sets the handler that will be called after all the middleware has been invoked.
124 167
 // This is set to macaron.Router in a macaron.Classic().
125 168
 func (m *Macaron) Action(handler Handler) {
126
-	validateHandler(handler)
169
+	handler = validateAndWrapHandler(handler)
127 170
 	m.action = handler
128 171
 }
129 172
 
@@ -139,7 +182,7 @@ func (m *Macaron) Before(handler BeforeHandler) {
139 182
 // and panics if the handler is not a callable func.
140 183
 // Middleware Handlers are invoked in the order that they are added.
141 184
 func (m *Macaron) Use(handler Handler) {
142
-	validateHandler(handler)
185
+	handler = validateAndWrapHandler(handler)
143 186
 	m.handlers = append(m.handlers, handler)
144 187
 }
145 188
 

+ 22 - 7
vendor/gopkg.in/macaron.v1/router.go

@@ -82,6 +82,9 @@ type Router struct {
82 82
 	groups              []group
83 83
 	notFound            http.HandlerFunc
84 84
 	internalServerError func(*Context, error)
85
+
86
+	// handlerWrapper is used to wrap arbitrary function from Handler to inject.FastInvoker.
87
+	handlerWrapper func(Handler) Handler
85 88
 }
86 89
 
87 90
 func NewRouter() *Router {
@@ -115,7 +118,7 @@ func (r *Route) Name(name string) {
115 118
 	if len(name) == 0 {
116 119
 		panic("route name cannot be empty")
117 120
 	} else if r.router.namedRoutes[name] != nil {
118
-		panic("route with given name already exists")
121
+		panic("route with given name already exists: " + name)
119 122
 	}
120 123
 	r.router.namedRoutes[name] = r.leaf
121 124
 }
@@ -173,7 +176,7 @@ func (r *Router) Handle(method string, pattern string, handlers []Handler) *Rout
173 176
 		h = append(h, handlers...)
174 177
 		handlers = h
175 178
 	}
176
-	validateHandlers(handlers)
179
+	handlers = validateAndWrapHandlers(handlers, r.handlerWrapper)
177 180
 
178 181
 	return r.handle(method, pattern, func(resp http.ResponseWriter, req *http.Request, params Params) {
179 182
 		c := r.m.createContext(resp, req)
@@ -251,11 +254,11 @@ func (r *Router) Combo(pattern string, h ...Handler) *ComboRouter {
251 254
 	return &ComboRouter{r, pattern, h, map[string]bool{}, nil}
252 255
 }
253 256
 
254
-// Configurable http.HandlerFunc which is called when no matching route is
257
+// NotFound configurates http.HandlerFunc which is called when no matching route is
255 258
 // found. If it is not set, http.NotFound is used.
256 259
 // Be sure to set 404 response code in your handler.
257 260
 func (r *Router) NotFound(handlers ...Handler) {
258
-	validateHandlers(handlers)
261
+	handlers = validateAndWrapHandlers(handlers)
259 262
 	r.notFound = func(rw http.ResponseWriter, req *http.Request) {
260 263
 		c := r.m.createContext(rw, req)
261 264
 		c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers))
@@ -265,11 +268,11 @@ func (r *Router) NotFound(handlers ...Handler) {
265 268
 	}
266 269
 }
267 270
 
268
-// Configurable handler which is called when route handler returns
271
+// InternalServerError configurates handler which is called when route handler returns
269 272
 // error. If it is not set, default handler is used.
270 273
 // Be sure to set 500 response code in your handler.
271 274
 func (r *Router) InternalServerError(handlers ...Handler) {
272
-	validateHandlers(handlers)
275
+	handlers = validateAndWrapHandlers(handlers)
273 276
 	r.internalServerError = func(c *Context, err error) {
274 277
 		c.index = 0
275 278
 		c.handlers = handlers
@@ -278,9 +281,21 @@ func (r *Router) InternalServerError(handlers ...Handler) {
278 281
 	}
279 282
 }
280 283
 
284
+// SetHandlerWrapper sets handlerWrapper for the router.
285
+func (r *Router) SetHandlerWrapper(f func(Handler) Handler) {
286
+	r.handlerWrapper = f
287
+}
288
+
281 289
 func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
282 290
 	if t, ok := r.routers[req.Method]; ok {
283
-		h, p, ok := t.Match(req.URL.Path)
291
+		// Fast match for static routes
292
+		leaf := r.getLeaf(req.Method, req.URL.Path)
293
+		if leaf != nil {
294
+			leaf.handle(rw, req, nil)
295
+			return
296
+		}
297
+
298
+		h, p, ok := t.Match(req.URL.EscapedPath())
284 299
 		if ok {
285 300
 			if splat, ok := p["*0"]; ok {
286 301
 				p["*"] = splat // Easy name.

+ 22 - 11
vendor/gopkg.in/macaron.v1/tree.go

@@ -261,6 +261,10 @@ func (t *Tree) Add(pattern string, handle Handle) *Leaf {
261 261
 }
262 262
 
263 263
 func (t *Tree) matchLeaf(globLevel int, url string, params Params) (Handle, bool) {
264
+	url, err := PathUnescape(url)
265
+	if err != nil {
266
+		return nil, false
267
+	}
264 268
 	for i := 0; i < len(t.leaves); i++ {
265 269
 		switch t.leaves[i].typ {
266 270
 		case _PATTERN_STATIC:
@@ -300,16 +304,20 @@ func (t *Tree) matchLeaf(globLevel int, url string, params Params) (Handle, bool
300 304
 }
301 305
 
302 306
 func (t *Tree) matchSubtree(globLevel int, segment, url string, params Params) (Handle, bool) {
307
+	unescapedSegment, err := PathUnescape(segment)
308
+	if err != nil {
309
+		return nil, false
310
+	}
303 311
 	for i := 0; i < len(t.subtrees); i++ {
304 312
 		switch t.subtrees[i].typ {
305 313
 		case _PATTERN_STATIC:
306
-			if t.subtrees[i].pattern == segment {
314
+			if t.subtrees[i].pattern == unescapedSegment {
307 315
 				if handle, ok := t.subtrees[i].matchNextSegment(globLevel, url, params); ok {
308 316
 					return handle, true
309 317
 				}
310 318
 			}
311 319
 		case _PATTERN_REGEXP:
312
-			results := t.subtrees[i].reg.FindStringSubmatch(segment)
320
+			results := t.subtrees[i].reg.FindStringSubmatch(unescapedSegment)
313 321
 			if len(results)-1 != len(t.subtrees[i].wildcards) {
314 322
 				break
315 323
 			}
@@ -322,12 +330,12 @@ func (t *Tree) matchSubtree(globLevel int, segment, url string, params Params) (
322 330
 			}
323 331
 		case _PATTERN_HOLDER:
324 332
 			if handle, ok := t.subtrees[i].matchNextSegment(globLevel+1, url, params); ok {
325
-				params[t.subtrees[i].wildcards[0]] = segment
333
+				params[t.subtrees[i].wildcards[0]] = unescapedSegment
326 334
 				return handle, true
327 335
 			}
328 336
 		case _PATTERN_MATCH_ALL:
329 337
 			if handle, ok := t.subtrees[i].matchNextSegment(globLevel+1, url, params); ok {
330
-				params["*"+com.ToStr(globLevel)] = segment
338
+				params["*"+com.ToStr(globLevel)] = unescapedSegment
331 339
 				return handle, true
332 340
 			}
333 341
 		}
@@ -335,19 +343,22 @@ func (t *Tree) matchSubtree(globLevel int, segment, url string, params Params) (
335 343
 
336 344
 	if len(t.leaves) > 0 {
337 345
 		leaf := t.leaves[len(t.leaves)-1]
346
+		unescapedURL, err := PathUnescape(segment + "/" + url)
347
+		if err != nil {
348
+			return nil, false
349
+		}
338 350
 		if leaf.typ == _PATTERN_PATH_EXT {
339
-			url = segment + "/" + url
340
-			j := strings.LastIndex(url, ".")
351
+			j := strings.LastIndex(unescapedURL, ".")
341 352
 			if j > -1 {
342
-				params[":path"] = url[:j]
343
-				params[":ext"] = url[j+1:]
353
+				params[":path"] = unescapedURL[:j]
354
+				params[":ext"] = unescapedURL[j+1:]
344 355
 			} else {
345
-				params[":path"] = url
356
+				params[":path"] = unescapedURL
346 357
 			}
347 358
 			return leaf.handle, true
348 359
 		} else if leaf.typ == _PATTERN_MATCH_ALL {
349
-			params["*"] = segment + "/" + url
350
-			params["*"+com.ToStr(globLevel)] = segment + "/" + url
360
+			params["*"] = unescapedURL
361
+			params["*"+com.ToStr(globLevel)] = unescapedURL
351 362
 			return leaf.handle, true
352 363
 		}
353 364
 	}

+ 25 - 0
vendor/gopkg.in/macaron.v1/util_go17.go

@@ -0,0 +1,25 @@
1
+// +build !go1.8
2
+
3
+// Copyright 2017 The Macaron Authors
4
+//
5
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
6
+// not use this file except in compliance with the License. You may obtain
7
+// a copy of the License at
8
+//
9
+//     http://www.apache.org/licenses/LICENSE-2.0
10
+//
11
+// Unless required by applicable law or agreed to in writing, software
12
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+// License for the specific language governing permissions and limitations
15
+// under the License.
16
+
17
+package macaron
18
+
19
+import "net/url"
20
+
21
+// PathUnescape unescapes a path. Ideally, this function would use
22
+// url.PathUnescape(..), but the function was not introduced until go1.8.
23
+func PathUnescape(s string) (string, error) {
24
+	return url.QueryUnescape(s)
25
+}

+ 24 - 0
vendor/gopkg.in/macaron.v1/util_go18.go

@@ -0,0 +1,24 @@
1
+// +build go1.8
2
+
3
+// Copyright 2017 The Macaron Authors
4
+//
5
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
6
+// not use this file except in compliance with the License. You may obtain
7
+// a copy of the License at
8
+//
9
+//     http://www.apache.org/licenses/LICENSE-2.0
10
+//
11
+// Unless required by applicable law or agreed to in writing, software
12
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+// License for the specific language governing permissions and limitations
15
+// under the License.
16
+
17
+package macaron
18
+
19
+import "net/url"
20
+
21
+// PathUnescape unescapes a path.
22
+func PathUnescape(s string) (string, error) {
23
+	return url.PathUnescape(s)
24
+}

+ 6 - 6
vendor/vendor.json

@@ -33,10 +33,10 @@
33 33
 			"revisionTime": "2016-07-15T03:28:08Z"
34 34
 		},
35 35
 		{
36
-			"checksumSHA1": "ly9VLPE9GKo2U7mnbZyjb2LDQ3w=",
36
+			"checksumSHA1": "IrtvVIFBTQmk0+vM7g2xtka5SFg=",
37 37
 			"path": "github.com/Unknwon/com",
38
-			"revision": "28b053d5a2923b87ce8c5a08f3af779894a72758",
39
-			"revisionTime": "2015-10-08T13:54:07Z"
38
+			"revision": "7677a1d7c1137cd3dd5ba7a076d0c898a1ef4520",
39
+			"revisionTime": "2017-08-19T22:39:52Z"
40 40
 		},
41 41
 		{
42 42
 			"checksumSHA1": "GwPkXd1UL3D7F3IuHHM+V0r4MB4=",
@@ -1508,10 +1508,10 @@
1508 1508
 			"revisionTime": "2016-08-08T14:54:09Z"
1509 1509
 		},
1510 1510
 		{
1511
-			"checksumSHA1": "u1dW5zfo2SWot04r5cL8dTbmtcc=",
1511
+			"checksumSHA1": "VJKlO1AEWQivq2S4DvdmAJU2Fvs=",
1512 1512
 			"path": "gopkg.in/macaron.v1",
1513
-			"revision": "aa6b7ee41a182898a33d798c655df1cac9d2230b",
1514
-			"revisionTime": "2017-01-22T14:42:53Z"
1513
+			"revision": "75f2e9b42e99652f0d82b28ccb73648f44615faa",
1514
+			"revisionTime": "2017-11-24T00:20:17Z"
1515 1515
 		},
1516 1516
 		{
1517 1517
 			"checksumSHA1": "6QPjE+qflEBHg+JPJd9e4iQuRAk=",