making progress
This commit is contained in:
@@ -0,0 +1 @@
|
||||
ref: refs/heads/master
|
||||
@@ -0,0 +1,8 @@
|
||||
[core]
|
||||
repositoryformatversion = 0
|
||||
filemode = true
|
||||
bare = true
|
||||
ignorecase = true
|
||||
precomposeunicode = true
|
||||
[http]
|
||||
receivepack = true
|
||||
@@ -0,0 +1 @@
|
||||
Unnamed repository; edit this file 'description' to name the repository.
|
||||
+15
@@ -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+"$@"}
|
||||
:
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
#!/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 and messages that
|
||||
# would confuse 'git am'.
|
||||
|
||||
ret=0
|
||||
|
||||
test "" = "$(grep '^Signed-off-by: ' "$1" |
|
||||
sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || {
|
||||
echo >&2 Duplicate Signed-off-by lines.
|
||||
ret=1
|
||||
}
|
||||
|
||||
comment_re="$(
|
||||
{
|
||||
git config --get-regexp "^core\.comment(char|string)\$" ||
|
||||
echo '#'
|
||||
} | sed -n -e '
|
||||
${
|
||||
s/^[^ ]* //
|
||||
s|[][*./\]|\\&|g
|
||||
s/^auto$/[#;@!$%^&|:]/
|
||||
p
|
||||
}'
|
||||
)"
|
||||
scissors_line="^${comment_re} -\{8,\} >8 -\{8,\}\$"
|
||||
comment_line="^${comment_re}.*"
|
||||
blank_line='^[ ]*$'
|
||||
# Disallow lines starting with "diff -" or "Index: " in the body of the
|
||||
# message. Stop looking if we see a scissors line.
|
||||
line="$(sed -n -e "
|
||||
# Skip comments and blank lines at the start of the file.
|
||||
/${scissors_line}/q
|
||||
/${comment_line}/d
|
||||
/${blank_line}/d
|
||||
# The first paragraph will become the subject header so
|
||||
# does not need to be checked.
|
||||
: subject
|
||||
n
|
||||
/${scissors_line}/q
|
||||
/${blank_line}/!b subject
|
||||
# Check the body of the message for problematic
|
||||
# prefixes.
|
||||
: body
|
||||
n
|
||||
/${scissors_line}/q
|
||||
/${comment_line}/b body
|
||||
/^diff -/{p;q;}
|
||||
/^Index: /{p;q;}
|
||||
b body
|
||||
" "$1")"
|
||||
if test -n "$line"
|
||||
then
|
||||
echo >&2 "Message contains a diff that will confuse 'git am'."
|
||||
echo >&2 "To fix this indent the diff."
|
||||
ret=1
|
||||
fi
|
||||
|
||||
exit $ret
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
#!/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 2) and last update token
|
||||
# formatted as a string and outputs to stdout a new update token and
|
||||
# all files that have been modified since the update token. 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, $last_update_token) = @ARGV;
|
||||
|
||||
# Uncomment for debugging
|
||||
# print STDERR "$0 $version $last_update_token\n";
|
||||
|
||||
# Check the hook interface version
|
||||
if ($version ne 2) {
|
||||
die "Unsupported query-fsmonitor hook version '$version'.\n" .
|
||||
"Falling back to scanning...\n";
|
||||
}
|
||||
|
||||
my $git_work_tree = get_working_dir();
|
||||
|
||||
my $json_pkg;
|
||||
eval {
|
||||
require JSON::XS;
|
||||
$json_pkg = "JSON::XS";
|
||||
1;
|
||||
} or do {
|
||||
require JSON::PP;
|
||||
$json_pkg = "JSON::PP";
|
||||
};
|
||||
|
||||
launch_watchman();
|
||||
|
||||
sub launch_watchman {
|
||||
my $o = watchman_query();
|
||||
if (is_work_tree_watched($o)) {
|
||||
output_result($o->{clock}, @{$o->{files}});
|
||||
}
|
||||
}
|
||||
|
||||
sub output_result {
|
||||
my ($clockid, @files) = @_;
|
||||
|
||||
# Uncomment for debugging watchman output
|
||||
# open (my $fh, ">", ".git/watchman-output.out");
|
||||
# binmode $fh, ":utf8";
|
||||
# print $fh "$clockid\n@files\n";
|
||||
# close $fh;
|
||||
|
||||
binmode STDOUT, ":utf8";
|
||||
print $clockid;
|
||||
print "\0";
|
||||
local $, = "\0";
|
||||
print @files;
|
||||
}
|
||||
|
||||
sub watchman_clock {
|
||||
my $response = qx/watchman clock "$git_work_tree"/;
|
||||
die "Failed to get clock id on '$git_work_tree'.\n" .
|
||||
"Falling back to scanning...\n" if $? != 0;
|
||||
|
||||
return $json_pkg->new->utf8->decode($response);
|
||||
}
|
||||
|
||||
sub watchman_query {
|
||||
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 $last_update_token but not from the .git folder.
|
||||
#
|
||||
# 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.
|
||||
my $last_update_line = "";
|
||||
if (substr($last_update_token, 0, 1) eq "c") {
|
||||
$last_update_token = "\"$last_update_token\"";
|
||||
$last_update_line = qq[\n"since": $last_update_token,];
|
||||
}
|
||||
my $query = <<" END";
|
||||
["query", "$git_work_tree", {$last_update_line
|
||||
"fields": ["name"],
|
||||
"expression": ["not", ["dirname", ".git"]]
|
||||
}]
|
||||
END
|
||||
|
||||
# Uncomment for debugging the watchman query
|
||||
# open (my $fh, ">", ".git/watchman-query.json");
|
||||
# print $fh $query;
|
||||
# close $fh;
|
||||
|
||||
print CHLD_IN $query;
|
||||
close CHLD_IN;
|
||||
my $response = do {local $/; <CHLD_OUT>};
|
||||
|
||||
# Uncomment for debugging the watch response
|
||||
# open ($fh, ">", ".git/watchman-response.json");
|
||||
# print $fh $response;
|
||||
# close $fh;
|
||||
|
||||
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 =~ /^\{/;
|
||||
|
||||
return $json_pkg->new->utf8->decode($response);
|
||||
}
|
||||
|
||||
sub is_work_tree_watched {
|
||||
my ($output) = @_;
|
||||
my $error = $output->{error};
|
||||
if ($error and $error =~ m/unable to resolve root .* directory (.*) is not watched/) {
|
||||
my $response = qx/watchman watch "$git_work_tree"/;
|
||||
die "Failed to make watchman watch '$git_work_tree'.\n" .
|
||||
"Falling back to scanning...\n" if $? != 0;
|
||||
$output = $json_pkg->new->utf8->decode($response);
|
||||
$error = $output->{error};
|
||||
die "Watchman: $error.\n" .
|
||||
"Falling back to scanning...\n" if $error;
|
||||
|
||||
# Uncomment for debugging watchman output
|
||||
# open (my $fh, ">", ".git/watchman-output.out");
|
||||
# close $fh;
|
||||
|
||||
# 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.
|
||||
my $o = watchman_clock();
|
||||
$error = $o->{error};
|
||||
|
||||
die "Watchman: $error.\n" .
|
||||
"Falling back to scanning...\n" if $error;
|
||||
|
||||
output_result($o->{clock}, ("/"));
|
||||
return 0;
|
||||
}
|
||||
|
||||
die "Watchman: $error.\n" .
|
||||
"Falling back to scanning...\n" if $error;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
sub get_working_dir {
|
||||
my $working_dir;
|
||||
if ($^O =~ 'msys' || $^O =~ 'cygwin') {
|
||||
$working_dir = Win32::GetCwd();
|
||||
$working_dir =~ tr/\\/\//;
|
||||
} else {
|
||||
require Cwd;
|
||||
$working_dir = Cwd::cwd();
|
||||
}
|
||||
|
||||
return $working_dir;
|
||||
}
|
||||
+8
@@ -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
|
||||
+14
@@ -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+"$@"}
|
||||
:
|
||||
+49
@@ -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 --type=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-index --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 --
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# An example hook script to verify what is about to be committed.
|
||||
# Called by "git merge" with no arguments. The hook should
|
||||
# exit with non-zero status after issuing an appropriate message to
|
||||
# stderr if it wants to stop the merge commit.
|
||||
#
|
||||
# To enable this hook, rename this file to "pre-merge-commit".
|
||||
|
||||
. git-sh-setup
|
||||
test -x "$GIT_DIR/hooks/pre-commit" &&
|
||||
exec "$GIT_DIR/hooks/pre-commit"
|
||||
:
|
||||
+53
@@ -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 oid> <remote ref> <remote oid>
|
||||
#
|
||||
# This sample shows how to prevent push of commits where the log message starts
|
||||
# with "WIP" (work in progress).
|
||||
|
||||
remote="$1"
|
||||
url="$2"
|
||||
|
||||
zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')
|
||||
|
||||
while read local_ref local_oid remote_ref remote_oid
|
||||
do
|
||||
if test "$local_oid" = "$zero"
|
||||
then
|
||||
# Handle delete
|
||||
:
|
||||
else
|
||||
if test "$remote_oid" = "$zero"
|
||||
then
|
||||
# New branch, examine all commits
|
||||
range="$local_oid"
|
||||
else
|
||||
# Update to existing branch, examine new commits
|
||||
range="$remote_oid..$local_oid"
|
||||
fi
|
||||
|
||||
# Check for WIP commit
|
||||
commit=$(git rev-list -n 1 --grep '^WIP' "$range")
|
||||
if test -n "$commit"
|
||||
then
|
||||
echo >&2 "Found WIP commit in $local_ref, not pushing"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
exit 0
|
||||
+169
@@ -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
|
||||
+24
@@ -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
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#!/bin/sh
|
||||
|
||||
# An example hook script to update a checked-out tree on a git push.
|
||||
#
|
||||
# This hook is invoked by git-receive-pack(1) when it reacts to git
|
||||
# push and updates reference(s) in its repository, and when the push
|
||||
# tries to update the branch that is currently checked out and the
|
||||
# receive.denyCurrentBranch configuration variable is set to
|
||||
# updateInstead.
|
||||
#
|
||||
# By default, such a push is refused if the working tree and the index
|
||||
# of the remote repository has any difference from the currently
|
||||
# checked out commit; when both the working tree and the index match
|
||||
# the current commit, they are updated to match the newly pushed tip
|
||||
# of the branch. This hook is to be used to override the default
|
||||
# behaviour; however the code below reimplements the default behaviour
|
||||
# as a starting point for convenient modification.
|
||||
#
|
||||
# The hook receives the commit with which the tip of the current
|
||||
# branch is going to be updated:
|
||||
commit=$1
|
||||
|
||||
# It can exit with a non-zero status to refuse the push (when it does
|
||||
# so, it must not modify the index or the working tree).
|
||||
die () {
|
||||
echo >&2 "$*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Or it can make any necessary changes to the working tree and to the
|
||||
# index to bring them to the desired state when the tip of the current
|
||||
# branch is updated to the new commit, and exit with a zero status.
|
||||
#
|
||||
# For example, the hook can simply run git read-tree -u -m HEAD "$1"
|
||||
# in order to emulate git fetch that is run in the reverse direction
|
||||
# with git push, as the two-tree form of git read-tree -u -m is
|
||||
# essentially the same as git switch or git checkout that switches
|
||||
# branches while keeping the local changes in the working tree that do
|
||||
# not interfere with the difference between the branches.
|
||||
|
||||
# The below is a more-or-less exact translation to shell of the C code
|
||||
# for the default behaviour for git's push-to-checkout hook defined in
|
||||
# the push_to_deploy() function in builtin/receive-pack.c.
|
||||
#
|
||||
# Note that the hook will be executed from the repository directory,
|
||||
# not from the working tree, so if you want to perform operations on
|
||||
# the working tree, you will have to adapt your code accordingly, e.g.
|
||||
# by adding "cd .." or using relative paths.
|
||||
|
||||
if ! git update-index -q --ignore-submodules --refresh
|
||||
then
|
||||
die "Up-to-date check failed"
|
||||
fi
|
||||
|
||||
if ! git diff-files --quiet --ignore-submodules --
|
||||
then
|
||||
die "Working directory has unstaged changes"
|
||||
fi
|
||||
|
||||
# This is a rough translation of:
|
||||
#
|
||||
# head_has_history() ? "HEAD" : EMPTY_TREE_SHA1_HEX
|
||||
if git cat-file -e HEAD 2>/dev/null
|
||||
then
|
||||
head=HEAD
|
||||
else
|
||||
head=$(git hash-object -t tree --stdin </dev/null)
|
||||
fi
|
||||
|
||||
if ! git diff-index --quiet --cached --ignore-submodules $head --
|
||||
then
|
||||
die "Working directory has staged changes"
|
||||
fi
|
||||
|
||||
if ! git read-tree -u -m "$commit"
|
||||
then
|
||||
die "Could not update working tree to new HEAD"
|
||||
fi
|
||||
@@ -0,0 +1,77 @@
|
||||
#!/bin/sh
|
||||
|
||||
# An example hook script to validate a patch (and/or patch series) before
|
||||
# sending it via email.
|
||||
#
|
||||
# The hook should exit with non-zero status after issuing an appropriate
|
||||
# message if it wants to prevent the email(s) from being sent.
|
||||
#
|
||||
# To enable this hook, rename this file to "sendemail-validate".
|
||||
#
|
||||
# By default, it will only check that the patch(es) can be applied on top of
|
||||
# the default upstream branch without conflicts in a secondary worktree. After
|
||||
# validation (successful or not) of the last patch of a series, the worktree
|
||||
# will be deleted.
|
||||
#
|
||||
# The following config variables can be set to change the default remote and
|
||||
# remote ref that are used to apply the patches against:
|
||||
#
|
||||
# sendemail.validateRemote (default: origin)
|
||||
# sendemail.validateRemoteRef (default: HEAD)
|
||||
#
|
||||
# Replace the TODO placeholders with appropriate checks according to your
|
||||
# needs.
|
||||
|
||||
validate_cover_letter () {
|
||||
file="$1"
|
||||
# TODO: Replace with appropriate checks (e.g. spell checking).
|
||||
true
|
||||
}
|
||||
|
||||
validate_patch () {
|
||||
file="$1"
|
||||
# Ensure that the patch applies without conflicts.
|
||||
git am -3 "$file" || return
|
||||
# TODO: Replace with appropriate checks for this patch
|
||||
# (e.g. checkpatch.pl).
|
||||
true
|
||||
}
|
||||
|
||||
validate_series () {
|
||||
# TODO: Replace with appropriate checks for the whole series
|
||||
# (e.g. quick build, coding style checks, etc.).
|
||||
true
|
||||
}
|
||||
|
||||
# main -------------------------------------------------------------------------
|
||||
|
||||
if test "$GIT_SENDEMAIL_FILE_COUNTER" = 1
|
||||
then
|
||||
remote=$(git config --default origin --get sendemail.validateRemote) &&
|
||||
ref=$(git config --default HEAD --get sendemail.validateRemoteRef) &&
|
||||
worktree=$(mktemp --tmpdir -d sendemail-validate.XXXXXXX) &&
|
||||
git worktree add -fd --checkout "$worktree" "refs/remotes/$remote/$ref" &&
|
||||
git config --replace-all sendemail.validateWorktree "$worktree"
|
||||
else
|
||||
worktree=$(git config --get sendemail.validateWorktree)
|
||||
fi || {
|
||||
echo "sendemail-validate: error: failed to prepare worktree" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
unset GIT_DIR GIT_WORK_TREE
|
||||
cd "$worktree" &&
|
||||
|
||||
if grep -q "^diff --git " "$1"
|
||||
then
|
||||
validate_patch "$1"
|
||||
else
|
||||
validate_cover_letter "$1"
|
||||
fi &&
|
||||
|
||||
if test "$GIT_SENDEMAIL_FILE_COUNTER" = "$GIT_SENDEMAIL_FILE_TOTAL"
|
||||
then
|
||||
git config --unset-all sendemail.validateWorktree &&
|
||||
trap 'git worktree remove -ff "$worktree"' EXIT &&
|
||||
validate_series
|
||||
fi
|
||||
Executable
+128
@@ -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 --type=bool hooks.allowunannotated)
|
||||
allowdeletebranch=$(git config --type=bool hooks.allowdeletebranch)
|
||||
denycreatebranch=$(git config --type=bool hooks.denycreatebranch)
|
||||
allowdeletetag=$(git config --type=bool hooks.allowdeletetag)
|
||||
allowmodifytag=$(git config --type=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=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')
|
||||
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]
|
||||
# *~
|
||||
@@ -22,6 +22,8 @@ const RegisterPage = lazy(() => import('./pages/RegisterPage'))
|
||||
const DashboardPage = lazy(() => import('./pages/DashboardPage'))
|
||||
const ReposPage = lazy(() => import('./pages/ReposPage'))
|
||||
const RepoPage = lazy(() => import('./pages/RepoPage'))
|
||||
const RepoSettingsPage = lazy(() => import('./pages/RepoSettingsPage'))
|
||||
const RepoIssuesPage = lazy(() => import('./pages/RepoIssuesPage'))
|
||||
const RepoPRsPage = lazy(() => import('./pages/RepoPRsPage'))
|
||||
const PRDetailPage = lazy(() => import('./pages/PRDetailPage'))
|
||||
const PRsPage = lazy(() => import('./pages/PRsPage'))
|
||||
@@ -55,17 +57,16 @@ export default function App() {
|
||||
<CSRFBootstrap />
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
{/* Auth pages — full screen, no shell */}
|
||||
<Route path="/login" element={<S><LoginPage /></S>} />
|
||||
<Route path="/register" element={<S><RegisterPage /></S>} />
|
||||
|
||||
{/* Shell layout — explicit root path prevents ambiguous wildcard matching */}
|
||||
<Route path="/" element={<AppShell />}>
|
||||
<Route index element={<S><DashboardPage /></S>} />
|
||||
|
||||
{/* Repos — nested so /repos/:owner/:repo is unambiguous */}
|
||||
<Route path="repos" element={<S><ReposPage /></S>} />
|
||||
<Route path="repos/:owner/:repo" element={<S><RepoPage /></S>} />
|
||||
<Route path="repos/:owner/:repo/settings" element={<S><RepoSettingsPage /></S>} />
|
||||
<Route path="repos/:owner/:repo/issues" element={<S><RepoIssuesPage /></S>} />
|
||||
<Route path="repos/:owner/:repo/pulls" element={<S><RepoPRsPage /></S>} />
|
||||
<Route path="repos/:owner/:repo/pulls/:prId" element={<S><PRDetailPage /></S>} />
|
||||
|
||||
@@ -75,7 +76,6 @@ export default function App() {
|
||||
<Route path="profile" element={<S><ProfilePage /></S>} />
|
||||
<Route path="settings" element={<S><SettingsPage /></S>} />
|
||||
|
||||
{/* 404 within shell — shows a message, does NOT redirect */}
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
@@ -75,6 +75,8 @@ export const api = {
|
||||
request(path, schema, { method: 'POST', json: body }),
|
||||
put: <T>(path: string, schema: z.ZodType<T>, body: unknown) =>
|
||||
request(path, schema, { method: 'PUT', json: body }),
|
||||
patch: <T>(path: string, schema: z.ZodType<T>, body: unknown) =>
|
||||
request(path, schema, { method: 'PATCH', json: body }),
|
||||
delete: <T>(path: string, schema: z.ZodType<T>) =>
|
||||
request(path, schema, { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { z } from 'zod'
|
||||
import { api } from '../client'
|
||||
import type { Issue, IssueState } from '../../types/api'
|
||||
|
||||
const issueSchema = z.object({
|
||||
id: z.number(),
|
||||
repoId: z.number(),
|
||||
authorId: z.number(),
|
||||
authorName: z.string(),
|
||||
number: z.number(),
|
||||
title: z.string(),
|
||||
body: z.string(),
|
||||
state: z.enum(['open', 'closed']),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
})
|
||||
|
||||
const issuesSchema = z.array(issueSchema)
|
||||
|
||||
export function useIssues(owner: string, repo: string, state: IssueState = 'open') {
|
||||
return useQuery({
|
||||
queryKey: ['repos', owner, repo, 'issues', state],
|
||||
queryFn: () =>
|
||||
api.get<Issue[]>(`/api/v1/repos/${owner}/${repo}/issues?state=${state}`, issuesSchema),
|
||||
enabled: Boolean(owner && repo),
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateIssue(owner: string, repo: string) {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (data: { title: string; body?: string }) =>
|
||||
api.post<Issue>(`/api/v1/repos/${owner}/${repo}/issues`, issueSchema, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'issues'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useCloseIssue(owner: string, repo: string) {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (issueNum: number) =>
|
||||
api.post<Issue>(
|
||||
`/api/v1/repos/${owner}/${repo}/issues/${issueNum}/close`,
|
||||
issueSchema,
|
||||
{},
|
||||
),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'issues'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useReopenIssue(owner: string, repo: string) {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (issueNum: number) =>
|
||||
api.post<Issue>(
|
||||
`/api/v1/repos/${owner}/${repo}/issues/${issueNum}/reopen`,
|
||||
issueSchema,
|
||||
{},
|
||||
),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'issues'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -74,6 +74,30 @@ export function useRepoDiff(owner: string, name: string, base: string, head: str
|
||||
})
|
||||
}
|
||||
|
||||
export function useUpdateRepo(owner: string, name: string) {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (data: { description?: string; isPrivate?: boolean; defaultBranch?: string }) =>
|
||||
api.patch<Repository>(
|
||||
`/api/v1/repos/${owner}/${name}`,
|
||||
repositorySchema,
|
||||
data,
|
||||
),
|
||||
onSuccess: (updated) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
||||
queryClient.setQueryData(['repos', owner, name], updated)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeleteRepo(owner: string, name: string) {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: () => api.delete(`/api/v1/repos/${owner}/${name}`, z.any()),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['repos'] }),
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateRepo() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { z } from 'zod'
|
||||
import { api } from '../client'
|
||||
import type { SSHKey } from '../../types/api'
|
||||
|
||||
const sshKeySchema = z.object({
|
||||
id: z.number(),
|
||||
userId: z.number(),
|
||||
title: z.string(),
|
||||
fingerprint: z.string(),
|
||||
publicKey: z.string(),
|
||||
createdAt: z.string(),
|
||||
})
|
||||
|
||||
const sshKeysSchema = z.array(sshKeySchema)
|
||||
|
||||
export function useSSHKeys() {
|
||||
return useQuery({
|
||||
queryKey: ['user', 'keys'],
|
||||
queryFn: () => api.get<SSHKey[]>('/api/v1/user/keys', sshKeysSchema),
|
||||
})
|
||||
}
|
||||
|
||||
export function useAddSSHKey() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (data: { title: string; publicKey: string }) =>
|
||||
api.post<SSHKey>('/api/v1/user/keys', sshKeySchema, data),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['user', 'keys'] }),
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeleteSSHKey() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (keyId: number) =>
|
||||
api.delete(`/api/v1/user/keys/${keyId}`, z.any()),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['user', 'keys'] }),
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { useParams, Link } from 'react-router-dom'
|
||||
import { usePR } from '../api/queries/prs'
|
||||
import { useRepoDiff } from '../api/queries/repos'
|
||||
import { DiffViewer } from '../components/diff/DiffViewer'
|
||||
import { MobileComment } from '../components/diff/MobileComment'
|
||||
import { Skeleton } from '../ui/Skeleton'
|
||||
@@ -9,6 +10,11 @@ import { cn } from '../lib/utils'
|
||||
export default function PRDetailPage() {
|
||||
const { owner = '', repo = '', prId = '' } = useParams<{ owner: string; repo: string; prId: string }>()
|
||||
const { data: pr, isLoading, isError } = usePR(owner, repo, parseInt(prId, 10))
|
||||
const { data: diffs } = useRepoDiff(
|
||||
owner, repo,
|
||||
pr?.targetBranch ?? '',
|
||||
pr?.sourceBranch ?? '',
|
||||
)
|
||||
const [comment, setComment] = useState<{ file: string; line: number } | null>(null)
|
||||
|
||||
if (isLoading) {
|
||||
@@ -73,8 +79,7 @@ export default function PRDetailPage() {
|
||||
Files changed
|
||||
</h2>
|
||||
|
||||
{/* Demo diff — real diff loads when repo has commits on both branches */}
|
||||
<DiffViewer files={DEMO_DIFF} />
|
||||
<DiffViewer files={diffs ?? []} />
|
||||
</div>
|
||||
|
||||
{/* Mobile comment sheet */}
|
||||
@@ -88,22 +93,3 @@ export default function PRDetailPage() {
|
||||
)
|
||||
}
|
||||
|
||||
// Demo diff to show the component before real git data is available
|
||||
const DEMO_DIFF = [
|
||||
{
|
||||
path: 'README.md',
|
||||
additions: 6,
|
||||
deletions: 1,
|
||||
patch: `@@ -1,3 +1,8 @@
|
||||
-# Project
|
||||
+# My Project
|
||||
+
|
||||
+A sovereign, federated git collaboration platform.
|
||||
+
|
||||
+## Features
|
||||
+- Fast Go backend
|
||||
+- React 18 frontend
|
||||
+- ActivityPub federation
|
||||
`,
|
||||
},
|
||||
]
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useState } from 'react'
|
||||
import { useParams, Link } from 'react-router-dom'
|
||||
import { useIssues, useCreateIssue, useCloseIssue, useReopenIssue } from '../api/queries/issues'
|
||||
import { cn } from '../lib/utils'
|
||||
import type { IssueState } from '../types/api'
|
||||
|
||||
export default function RepoIssuesPage() {
|
||||
const { owner = '', repo = '' } = useParams<{ owner: string; repo: string }>()
|
||||
const [state, setState] = useState<IssueState>('open')
|
||||
const [showNew, setShowNew] = useState(false)
|
||||
|
||||
const { data: issues, isLoading } = useIssues(owner, repo, state)
|
||||
const createIssue = useCreateIssue(owner, repo)
|
||||
const closeIssue = useCloseIssue(owner, repo)
|
||||
const reopenIssue = useReopenIssue(owner, repo)
|
||||
|
||||
const [title, setTitle] = useState('')
|
||||
const [body, setBody] = useState('')
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!title.trim()) return
|
||||
await createIssue.mutateAsync({ title: title.trim(), body })
|
||||
setTitle(''); setBody(''); setShowNew(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4 md:px-6 py-6">
|
||||
<div className="flex items-center gap-1 text-sm mb-4">
|
||||
<Link to={`/repos/${owner}/${repo}`} className="text-[#0052CC] hover:underline">{repo}</Link>
|
||||
<span className="text-[#5E6C84]">/</span>
|
||||
<span className="font-semibold text-[#172B4D]">Issues</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h1 className="text-xl font-semibold text-[#172B4D]">Issues</h1>
|
||||
<button onClick={() => setShowNew(true)}
|
||||
className="px-3 py-2 rounded bg-[#0052CC] text-white text-sm font-medium hover:bg-[#0065FF] min-h-[44px]">
|
||||
New issue
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showNew && (
|
||||
<form onSubmit={handleCreate} className="mb-6 p-5 border border-[#4C9AFF] rounded bg-white space-y-3">
|
||||
<h2 className="text-sm font-semibold text-[#172B4D]">New Issue</h2>
|
||||
<input value={title} onChange={e => setTitle(e.target.value)} placeholder="Title" required
|
||||
className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF]" />
|
||||
<textarea value={body} onChange={e => setBody(e.target.value)} placeholder="Description (optional)" rows={4}
|
||||
className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm resize-none focus:outline-none focus:border-[#4C9AFF]" />
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" disabled={createIssue.isPending || !title.trim()}
|
||||
className="px-4 py-2 rounded bg-[#0052CC] text-white text-sm hover:bg-[#0065FF] disabled:opacity-50 min-h-[44px]">
|
||||
{createIssue.isPending ? 'Submitting…' : 'Submit'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setShowNew(false)}
|
||||
className="px-4 py-2 rounded border border-[#DFE1E6] text-sm text-[#172B4D] hover:bg-[#F4F5F7] min-h-[44px]">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="flex gap-1 mb-4 border-b border-[#DFE1E6]">
|
||||
{(['open', 'closed'] as IssueState[]).map(s => {
|
||||
const count = issues?.filter(i => i.state === s).length ?? 0
|
||||
return (
|
||||
<button key={s} onClick={() => setState(s)}
|
||||
className={cn('px-4 py-2 text-sm font-medium capitalize border-b-2 -mb-px min-h-[44px]',
|
||||
state === s ? 'border-[#0052CC] text-[#0052CC]' : 'border-transparent text-[#5E6C84] hover:text-[#172B4D]')}>
|
||||
{s} {count > 0 && `(${count})`}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-sm text-[#5E6C84] py-4">Loading…</p>
|
||||
) : !issues?.length ? (
|
||||
<p className="text-sm text-[#5E6C84] py-8 text-center">No {state} issues.</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{issues.map(issue => (
|
||||
<div key={issue.id}
|
||||
className="flex items-start gap-3 p-4 border border-[#DFE1E6] rounded hover:bg-[#FAFBFC]">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill={issue.state === 'open' ? '#00875A' : '#5E6C84'}
|
||||
className="mt-0.5 shrink-0">
|
||||
<path d="M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm9 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-.25-6.25a.75.75 0 0 0-1.5 0v3.5a.75.75 0 0 0 1.5 0v-3.5Z"/>
|
||||
</svg>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-[#172B4D]">#{issue.number} {issue.title}</p>
|
||||
<p className="text-xs text-[#5E6C84] mt-0.5">
|
||||
opened by {issue.authorName} · {new Date(issue.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => issue.state === 'open'
|
||||
? closeIssue.mutate(issue.number)
|
||||
: reopenIssue.mutate(issue.number)
|
||||
}
|
||||
className="text-xs px-3 py-1.5 rounded border border-[#DFE1E6] text-[#5E6C84] hover:bg-[#F4F5F7] shrink-0 min-h-[32px]">
|
||||
{issue.state === 'open' ? 'Close' : 'Reopen'}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -39,7 +39,7 @@ export default function RepoPage() {
|
||||
<GettingStarted owner={owner} repoName={repoName} branch={branch} cloneUrl={cloneUrl} />
|
||||
) : (
|
||||
<>
|
||||
{/* Branch pill + PR link */}
|
||||
{/* Branch pill + repo nav tabs */}
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<div className="flex items-center gap-1.5 px-2.5 py-1.5 border border-[#DFE1E6] rounded text-sm text-[#172B4D]">
|
||||
<svg width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24">
|
||||
@@ -47,9 +47,9 @@ export default function RepoPage() {
|
||||
</svg>
|
||||
{branch}
|
||||
</div>
|
||||
<Link to={`/repos/${owner}/${repoName}/pulls`} className="text-sm text-[#0052CC] hover:underline">
|
||||
Pull requests
|
||||
</Link>
|
||||
<Link to={`/repos/${owner}/${repoName}/issues`} className="text-sm text-[#0052CC] hover:underline">Issues</Link>
|
||||
<Link to={`/repos/${owner}/${repoName}/pulls`} className="text-sm text-[#0052CC] hover:underline">Pull requests</Link>
|
||||
<Link to={`/repos/${owner}/${repoName}/settings`} className="text-sm text-[#5E6C84] hover:text-[#172B4D] hover:underline ml-auto">Settings</Link>
|
||||
</div>
|
||||
|
||||
<TreeBrowser owner={owner} repo={repoName} ref={branch} path={path} />
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useState } from 'react'
|
||||
import { useParams, Link, useNavigate } from 'react-router-dom'
|
||||
import { useRepo, useUpdateRepo, useDeleteRepo } from '../api/queries/repos'
|
||||
|
||||
export default function RepoSettingsPage() {
|
||||
const { owner = '', repo: repoName = '' } = useParams<{ owner: string; repo: string }>()
|
||||
const navigate = useNavigate()
|
||||
const { data: repo } = useRepo(owner, repoName)
|
||||
const updateRepo = useUpdateRepo(owner, repoName)
|
||||
const deleteRepo = useDeleteRepo(owner, repoName)
|
||||
|
||||
const [description, setDescription] = useState(repo?.description ?? '')
|
||||
const [isPrivate, setIsPrivate] = useState(repo?.isPrivate ?? false)
|
||||
const [confirmDelete, setConfirmDelete] = useState('')
|
||||
const [saved, setSaved] = useState(false)
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
await updateRepo.mutateAsync({ description, isPrivate })
|
||||
setSaved(true)
|
||||
setTimeout(() => setSaved(false), 2000)
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (confirmDelete !== repoName) return
|
||||
await deleteRepo.mutateAsync()
|
||||
navigate('/repos')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto px-4 md:px-6 py-6 space-y-8">
|
||||
<div className="flex items-center gap-1 text-sm">
|
||||
<Link to={`/repos/${owner}/${repoName}`} className="text-[#0052CC] hover:underline">{repoName}</Link>
|
||||
<span className="text-[#5E6C84]">/</span>
|
||||
<span className="font-semibold text-[#172B4D]">Settings</span>
|
||||
</div>
|
||||
|
||||
<h1 className="text-xl font-semibold text-[#172B4D]">Repository Settings</h1>
|
||||
|
||||
<section className="border border-[#DFE1E6] rounded-lg overflow-hidden">
|
||||
<div className="px-5 py-4 border-b border-[#DFE1E6] bg-[#FAFBFC]">
|
||||
<h2 className="text-sm font-semibold text-[#172B4D]">General</h2>
|
||||
</div>
|
||||
<form onSubmit={handleSave} className="px-5 py-5 space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-[#172B4D] mb-1">Repository name</label>
|
||||
<input value={repoName} disabled
|
||||
className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm bg-[#F4F5F7] text-[#5E6C84] cursor-not-allowed" />
|
||||
<p className="text-xs text-[#5E6C84] mt-1">Renaming requires migrating git remotes — coming soon.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-[#172B4D] mb-1">Description</label>
|
||||
<input value={description} onChange={e => setDescription(e.target.value)}
|
||||
placeholder="Short description of this repository"
|
||||
className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF]" />
|
||||
</div>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input type="checkbox" checked={isPrivate} onChange={e => setIsPrivate(e.target.checked)} />
|
||||
<span className="text-sm text-[#172B4D]">Private repository</span>
|
||||
</label>
|
||||
<div className="flex items-center gap-3">
|
||||
<button type="submit" disabled={updateRepo.isPending}
|
||||
className="px-4 py-2 rounded bg-[#0052CC] text-white text-sm font-medium hover:bg-[#0065FF] disabled:opacity-50 min-h-[44px]">
|
||||
{updateRepo.isPending ? 'Saving…' : 'Save changes'}
|
||||
</button>
|
||||
{saved && <span className="text-xs text-[#00875A] font-medium">Saved!</span>}
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="border border-[#FFEBE6] rounded-lg overflow-hidden">
|
||||
<div className="px-5 py-4 border-b border-[#FFEBE6] bg-[#FFEBE6]/50">
|
||||
<h2 className="text-sm font-semibold text-[#BF2600]">Danger zone</h2>
|
||||
</div>
|
||||
<div className="px-5 py-5 space-y-3">
|
||||
<p className="text-sm text-[#172B4D] font-medium">Delete this repository</p>
|
||||
<p className="text-xs text-[#5E6C84]">
|
||||
This action is permanent. Type <code className="font-mono bg-[#F4F5F7] px-1 rounded">{repoName}</code> to confirm.
|
||||
</p>
|
||||
<input value={confirmDelete} onChange={e => setConfirmDelete(e.target.value)}
|
||||
placeholder={repoName}
|
||||
className="w-full border border-[#DE350B] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#DE350B]" />
|
||||
<button onClick={handleDelete}
|
||||
disabled={confirmDelete !== repoName || deleteRepo.isPending}
|
||||
className="px-4 py-2 rounded bg-[#DE350B] text-white text-sm font-medium hover:bg-[#BF2600] disabled:opacity-40 min-h-[44px]">
|
||||
{deleteRepo.isPending ? 'Deleting…' : 'Delete repository'}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import { useSSHKeys, useAddSSHKey, useDeleteSSHKey } from '../api/queries/sshkeys'
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { user, logout } = useAuth()
|
||||
@@ -58,15 +59,7 @@ export default function SettingsPage() {
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{/* SSH keys placeholder */}
|
||||
<section className="border border-[#DFE1E6] rounded-lg overflow-hidden">
|
||||
<div className="px-5 py-4 border-b border-[#DFE1E6] bg-[#FAFBFC]">
|
||||
<h2 className="text-sm font-semibold text-[#172B4D]">SSH keys</h2>
|
||||
</div>
|
||||
<div className="px-5 py-5 text-sm text-[#5E6C84]">
|
||||
SSH key management coming soon.
|
||||
</div>
|
||||
</section>
|
||||
<SSHKeySection />
|
||||
|
||||
{/* Danger zone */}
|
||||
<section className="border border-[#FFEBE6] rounded-lg overflow-hidden">
|
||||
@@ -100,3 +93,75 @@ function Row({ label, value }: { label: string; value?: string }) {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SSHKeySection() {
|
||||
const { data: keys } = useSSHKeys()
|
||||
const addKey = useAddSSHKey()
|
||||
const deleteKey = useDeleteSSHKey()
|
||||
const [showAdd, setShowAdd] = useState(false)
|
||||
const [title, setTitle] = useState('')
|
||||
const [publicKey, setPublicKey] = useState('')
|
||||
|
||||
const handleAdd = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
await addKey.mutateAsync({ title, publicKey })
|
||||
setTitle(''); setPublicKey(''); setShowAdd(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="border border-[#DFE1E6] rounded-lg overflow-hidden">
|
||||
<div className="px-5 py-4 border-b border-[#DFE1E6] bg-[#FAFBFC] flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold text-[#172B4D]">SSH keys</h2>
|
||||
<button onClick={() => setShowAdd(s => !s)}
|
||||
className="text-xs text-[#0052CC] hover:underline font-medium">
|
||||
{showAdd ? 'Cancel' : '+ Add key'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showAdd && (
|
||||
<form onSubmit={handleAdd} className="px-5 py-4 border-b border-[#DFE1E6] space-y-3 bg-[#FAFBFC]">
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-[#172B4D] mb-1">Title</label>
|
||||
<input value={title} onChange={e => setTitle(e.target.value)} required placeholder="e.g. MacBook Pro"
|
||||
className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF]" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-[#172B4D] mb-1">Public key</label>
|
||||
<textarea value={publicKey} onChange={e => setPublicKey(e.target.value)} required rows={3}
|
||||
placeholder="ssh-ed25519 AAAA… or ssh-rsa AAAA…"
|
||||
className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-xs font-mono resize-none focus:outline-none focus:border-[#4C9AFF]" />
|
||||
</div>
|
||||
{addKey.isError && (
|
||||
<p className="text-xs text-[#DE350B]">{addKey.error instanceof Error ? addKey.error.message : 'Error'}</p>
|
||||
)}
|
||||
<button type="submit" disabled={addKey.isPending}
|
||||
className="px-4 py-2 rounded bg-[#0052CC] text-white text-sm font-medium hover:bg-[#0065FF] disabled:opacity-50 min-h-[44px]">
|
||||
{addKey.isPending ? 'Adding…' : 'Add SSH key'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{!keys?.length ? (
|
||||
<div className="px-5 py-5 text-sm text-[#5E6C84]">No SSH keys added yet.</div>
|
||||
) : (
|
||||
<ul>
|
||||
{keys.map(key => (
|
||||
<li key={key.id} className="flex items-center gap-3 px-5 py-3 border-b border-[#DFE1E6] last:border-0">
|
||||
<svg width="16" height="16" fill="none" stroke="#5E6C84" strokeWidth="1.5" viewBox="0 0 24 24" className="shrink-0">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 5.25a3 3 0 0 1 3 3m3 0a6 6 0 0 1-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 0 1 21.75 8.25Z" />
|
||||
</svg>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-[#172B4D] truncate">{key.title}</p>
|
||||
<p className="text-xs font-mono text-[#5E6C84] truncate">{key.fingerprint}</p>
|
||||
</div>
|
||||
<button onClick={() => deleteKey.mutate(key.id)}
|
||||
className="text-xs px-3 py-1.5 rounded border border-[#DE350B] text-[#DE350B] hover:bg-[#FFEBE6] shrink-0 min-h-[32px]">
|
||||
Delete
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -62,6 +62,30 @@ export interface Pipeline {
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export type IssueState = 'open' | 'closed'
|
||||
|
||||
export interface Issue {
|
||||
id: number
|
||||
repoId: number
|
||||
authorId: number
|
||||
authorName: string
|
||||
number: number
|
||||
title: string
|
||||
body: string
|
||||
state: IssueState
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface SSHKey {
|
||||
id: number
|
||||
userId: number
|
||||
title: string
|
||||
fingerprint: string
|
||||
publicKey: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
error: string
|
||||
status: number
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"xorm.io/xorm"
|
||||
|
||||
"github.com/forgeo/forgebucket/internal/config"
|
||||
"github.com/forgeo/forgebucket/internal/models"
|
||||
)
|
||||
|
||||
type GitHTTPHandler struct {
|
||||
db *xorm.Engine
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
func NewGitHTTPHandler(db *xorm.Engine, cfg *config.Config) *GitHTTPHandler {
|
||||
return &GitHTTPHandler{db: db, cfg: cfg}
|
||||
}
|
||||
|
||||
// ServeGit is the entry point for all git smart-HTTP requests.
|
||||
// URL shape: /{owner}/{repo}.git/{service}
|
||||
func (h *GitHTTPHandler) ServeGit(w http.ResponseWriter, r *http.Request) {
|
||||
owner := chi.URLParam(r, "owner")
|
||||
repoGit := chi.URLParam(r, "repoGit") // e.g. "myrepo.git"
|
||||
repoName := strings.TrimSuffix(repoGit, ".git")
|
||||
|
||||
// Resolve repo from DB
|
||||
var ownerUser models.User
|
||||
if found, _ := h.db.Where("username = ?", owner).Get(&ownerUser); !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
var repo models.Repository
|
||||
if found, _ := h.db.Where("owner_id = ? AND name = ?", ownerUser.ID, repoName).Get(&repo); !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Determine service from URL / query string
|
||||
service := r.URL.Query().Get("service")
|
||||
if service == "" {
|
||||
// POST bodies encode the service in the path
|
||||
path := r.URL.Path
|
||||
if strings.HasSuffix(path, "/git-upload-pack") {
|
||||
service = "git-upload-pack"
|
||||
} else if strings.HasSuffix(path, "/git-receive-pack") {
|
||||
service = "git-receive-pack"
|
||||
}
|
||||
}
|
||||
|
||||
// Require authentication for push; allow anonymous read for public repos
|
||||
var authedUser string
|
||||
user, authed := h.basicAuth(r)
|
||||
if authed {
|
||||
authedUser = user
|
||||
} else if service == "git-receive-pack" || repo.IsPrivate {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="ForgeBucket"`)
|
||||
http.Error(w, "authentication required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Build PATH_INFO: /{reponame}.git/{suffix}
|
||||
// chi wildcard gives us everything after /{owner}/{repoGit}
|
||||
suffix := chi.URLParam(r, "*")
|
||||
if suffix == "" {
|
||||
suffix = "/"
|
||||
} else if !strings.HasPrefix(suffix, "/") {
|
||||
suffix = "/" + suffix
|
||||
}
|
||||
pathInfo := "/" + repoGit + suffix
|
||||
|
||||
projectRoot := filepath.Dir(repo.DiskPath)
|
||||
|
||||
env := []string{
|
||||
"GIT_PROJECT_ROOT=" + projectRoot,
|
||||
"GIT_HTTP_EXPORT_ALL=1",
|
||||
"PATH_INFO=" + pathInfo,
|
||||
"QUERY_STRING=" + r.URL.RawQuery,
|
||||
"REQUEST_METHOD=" + r.Method,
|
||||
"SERVER_PROTOCOL=HTTP/1.1",
|
||||
"SERVER_SOFTWARE=ForgeBucket/1.0",
|
||||
"REMOTE_ADDR=" + r.RemoteAddr,
|
||||
"HOME=/tmp",
|
||||
"GIT_TERMINAL_PROMPT=0",
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); ct != "" {
|
||||
env = append(env, "CONTENT_TYPE="+ct)
|
||||
}
|
||||
if cl := r.ContentLength; cl > 0 {
|
||||
env = append(env, "CONTENT_LENGTH="+strconv.FormatInt(cl, 10))
|
||||
}
|
||||
if authedUser != "" {
|
||||
env = append(env, "REMOTE_USER="+authedUser)
|
||||
}
|
||||
|
||||
gitExec, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
http.Error(w, "git not found on server", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if err := runGitBackend(r.Context(), w, r.Body, gitExec, env); err != nil {
|
||||
http.Error(w, fmt.Sprintf("git http-backend: %v", err), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// basicAuth validates HTTP Basic Auth credentials against the DB.
|
||||
func (h *GitHTTPHandler) basicAuth(r *http.Request) (username string, ok bool) {
|
||||
u, p, hasAuth := r.BasicAuth()
|
||||
if !hasAuth {
|
||||
return "", false
|
||||
}
|
||||
var user models.User
|
||||
found, _ := h.db.Where("username = ?", u).Get(&user)
|
||||
if !found {
|
||||
return "", false
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(p)) != nil {
|
||||
return "", false
|
||||
}
|
||||
return u, true
|
||||
}
|
||||
|
||||
// runGitBackend executes `git http-backend` as a CGI subprocess and forwards
|
||||
// its response (headers + body) to the HTTP response writer.
|
||||
func runGitBackend(ctx context.Context, w http.ResponseWriter, body io.Reader, gitExec string, env []string) error {
|
||||
cmd := exec.CommandContext(ctx, gitExec, "http-backend")
|
||||
cmd.Env = env
|
||||
|
||||
pr, pw := io.Pipe()
|
||||
cmd.Stdout = pw
|
||||
cmd.Stdin = body
|
||||
|
||||
var stderrBuf strings.Builder
|
||||
cmd.Stderr = &stderrBuf
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("start: %w", err)
|
||||
}
|
||||
|
||||
// Close write-end of pipe once git finishes
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
err := cmd.Wait()
|
||||
pw.Close()
|
||||
done <- err
|
||||
}()
|
||||
|
||||
// Parse CGI response: headers then body
|
||||
br := bufio.NewReader(pr)
|
||||
statusCode := http.StatusOK
|
||||
|
||||
for {
|
||||
line, err := br.ReadString('\n')
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if line == "" {
|
||||
break
|
||||
}
|
||||
if strings.HasPrefix(line, "Status:") {
|
||||
rest := strings.TrimSpace(strings.TrimPrefix(line, "Status:"))
|
||||
if parts := strings.SplitN(rest, " ", 2); len(parts) >= 1 {
|
||||
if code, e := strconv.Atoi(parts[0]); e == nil {
|
||||
statusCode = code
|
||||
}
|
||||
}
|
||||
} else if idx := strings.Index(line, ":"); idx > 0 {
|
||||
key := strings.TrimSpace(line[:idx])
|
||||
val := strings.TrimSpace(line[idx+1:])
|
||||
w.Header().Set(key, val)
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
io.Copy(w, br) //nolint:errcheck
|
||||
|
||||
waitErr := <-done
|
||||
if waitErr != nil && stderrBuf.Len() > 0 {
|
||||
return fmt.Errorf("%w: %s", waitErr, stderrBuf.String())
|
||||
}
|
||||
return waitErr
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"xorm.io/xorm"
|
||||
|
||||
"github.com/forgeo/forgebucket/internal/api/middleware"
|
||||
"github.com/forgeo/forgebucket/internal/models"
|
||||
)
|
||||
|
||||
type IssueHandler struct {
|
||||
db *xorm.Engine
|
||||
}
|
||||
|
||||
func NewIssueHandler(db *xorm.Engine) *IssueHandler {
|
||||
return &IssueHandler{db: db}
|
||||
}
|
||||
|
||||
type issueResponse struct {
|
||||
models.Issue
|
||||
AuthorName string `json:"authorName"`
|
||||
}
|
||||
|
||||
func (h *IssueHandler) enrichIssue(issue *models.Issue) issueResponse {
|
||||
var author models.User
|
||||
h.db.ID(issue.AuthorID).Get(&author)
|
||||
return issueResponse{Issue: *issue, AuthorName: author.Username}
|
||||
}
|
||||
|
||||
func (h *IssueHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
repoID, ok := h.repoID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
state := r.URL.Query().Get("state")
|
||||
if state == "" {
|
||||
state = "open"
|
||||
}
|
||||
|
||||
var issues []models.Issue
|
||||
if err := h.db.Where("repo_id = ? AND state = ?", repoID, state).
|
||||
OrderBy("id DESC").Find(&issues); err != nil {
|
||||
jsonError(w, "could not list issues", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
result := make([]issueResponse, len(issues))
|
||||
for i := range issues {
|
||||
result[i] = h.enrichIssue(&issues[i])
|
||||
}
|
||||
if result == nil {
|
||||
result = []issueResponse{}
|
||||
}
|
||||
jsonOK(w, result)
|
||||
}
|
||||
|
||||
func (h *IssueHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
repoID, ok := h.repoID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
authorID, _ := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Title == "" {
|
||||
jsonError(w, "title is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Auto-increment issue number per repo
|
||||
count, _ := h.db.Where("repo_id = ?", repoID).Count(&models.Issue{})
|
||||
number := int(count) + 1
|
||||
|
||||
issue := &models.Issue{
|
||||
RepoID: repoID,
|
||||
AuthorID: authorID,
|
||||
Number: number,
|
||||
Title: body.Title,
|
||||
Body: body.Body,
|
||||
State: models.IssueStateOpen,
|
||||
}
|
||||
if _, err := h.db.Insert(issue); err != nil {
|
||||
jsonError(w, "could not create issue", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(h.enrichIssue(issue))
|
||||
}
|
||||
|
||||
func (h *IssueHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
issue, ok := h.lookupIssue(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
jsonOK(w, h.enrichIssue(issue))
|
||||
}
|
||||
|
||||
func (h *IssueHandler) Close(w http.ResponseWriter, r *http.Request) {
|
||||
issue, ok := h.lookupIssue(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
issue.State = models.IssueStateClosed
|
||||
if _, err := h.db.ID(issue.ID).Cols("state").Update(issue); err != nil {
|
||||
jsonError(w, "could not close issue", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
jsonOK(w, h.enrichIssue(issue))
|
||||
}
|
||||
|
||||
func (h *IssueHandler) Reopen(w http.ResponseWriter, r *http.Request) {
|
||||
issue, ok := h.lookupIssue(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
issue.State = models.IssueStateOpen
|
||||
if _, err := h.db.ID(issue.ID).Cols("state").Update(issue); err != nil {
|
||||
jsonError(w, "could not reopen issue", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
jsonOK(w, h.enrichIssue(issue))
|
||||
}
|
||||
|
||||
func (h *IssueHandler) repoID(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||
ownerName := chi.URLParam(r, "owner")
|
||||
repoName := chi.URLParam(r, "repo")
|
||||
|
||||
var owner models.User
|
||||
if found, _ := h.db.Where("username = ?", ownerName).Get(&owner); !found {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return 0, false
|
||||
}
|
||||
var repo models.Repository
|
||||
if found, _ := h.db.Where("owner_id = ? AND name = ?", owner.ID, repoName).Get(&repo); !found {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return 0, false
|
||||
}
|
||||
return repo.ID, true
|
||||
}
|
||||
|
||||
func (h *IssueHandler) lookupIssue(w http.ResponseWriter, r *http.Request) (*models.Issue, bool) {
|
||||
repoID, ok := h.repoID(w, r)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
issueNum, err := strconv.Atoi(chi.URLParam(r, "issueNum"))
|
||||
if err != nil {
|
||||
jsonError(w, "invalid issue number", http.StatusBadRequest)
|
||||
return nil, false
|
||||
}
|
||||
var issue models.Issue
|
||||
if found, _ := h.db.Where("repo_id = ? AND number = ?", repoID, issueNum).Get(&issue); !found {
|
||||
jsonError(w, "issue not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
return &issue, true
|
||||
}
|
||||
@@ -51,13 +51,9 @@ func (h *RepoHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch owner username once (all repos belong to the same user in this query)
|
||||
var owner models.User
|
||||
h.db.ID(userID).Get(&owner)
|
||||
|
||||
result := make([]repoResponse, len(repos))
|
||||
for i, repo := range repos {
|
||||
result[i] = repoResponse{Repository: repo, OwnerName: owner.Username}
|
||||
for i := range repos {
|
||||
result[i] = h.withOwnerName(&repos[i])
|
||||
}
|
||||
jsonOK(w, result)
|
||||
}
|
||||
@@ -193,6 +189,64 @@ func (h *RepoHandler) Commits(w http.ResponseWriter, r *http.Request) {
|
||||
jsonOK(w, commits)
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
repo, ok := h.lookupRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Description *string `json:"description"`
|
||||
IsPrivate *bool `json:"isPrivate"`
|
||||
DefaultBranch *string `json:"defaultBranch"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
cols := []string{}
|
||||
if body.Description != nil {
|
||||
repo.Description = *body.Description
|
||||
cols = append(cols, "description")
|
||||
}
|
||||
if body.IsPrivate != nil {
|
||||
repo.IsPrivate = *body.IsPrivate
|
||||
cols = append(cols, "is_private")
|
||||
}
|
||||
if body.DefaultBranch != nil {
|
||||
repo.DefaultBranch = *body.DefaultBranch
|
||||
cols = append(cols, "default_branch")
|
||||
}
|
||||
|
||||
if len(cols) > 0 {
|
||||
if _, err := h.db.ID(repo.ID).Cols(cols...).Update(repo); err != nil {
|
||||
jsonError(w, "could not update repository", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
jsonOK(w, h.withOwnerName(repo))
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
repo, ok := h.lookupRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if callerID != repo.OwnerID {
|
||||
jsonError(w, "only the owner can delete a repository", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.db.ID(repo.ID).Delete(&models.Repository{}); err != nil {
|
||||
jsonError(w, "could not delete repository", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Diff(w http.ResponseWriter, r *http.Request) {
|
||||
repo, ok := h.lookupRepo(w, r)
|
||||
if !ok {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"golang.org/x/crypto/ssh"
|
||||
"xorm.io/xorm"
|
||||
|
||||
"github.com/forgeo/forgebucket/internal/api/middleware"
|
||||
"github.com/forgeo/forgebucket/internal/models"
|
||||
)
|
||||
|
||||
type SSHKeyHandler struct {
|
||||
db *xorm.Engine
|
||||
}
|
||||
|
||||
func NewSSHKeyHandler(db *xorm.Engine) *SSHKeyHandler {
|
||||
return &SSHKeyHandler{db: db}
|
||||
}
|
||||
|
||||
func (h *SSHKeyHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||
var keys []models.SSHKey
|
||||
if err := h.db.Where("user_id = ?", userID).Find(&keys); err != nil {
|
||||
jsonError(w, "could not list SSH keys", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if keys == nil {
|
||||
keys = []models.SSHKey{}
|
||||
}
|
||||
jsonOK(w, keys)
|
||||
}
|
||||
|
||||
func (h *SSHKeyHandler) Add(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
PublicKey string `json:"publicKey"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if body.Title == "" || body.PublicKey == "" {
|
||||
jsonError(w, "title and publicKey are required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse and validate the public key
|
||||
pubKeyBytes := []byte(strings.TrimSpace(body.PublicKey))
|
||||
pub, _, _, _, err := ssh.ParseAuthorizedKey(pubKeyBytes)
|
||||
if err != nil {
|
||||
jsonError(w, "invalid SSH public key format", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Compute MD5 fingerprint (standard display format)
|
||||
fingerprint := fingerprintMD5(pub)
|
||||
|
||||
key := &models.SSHKey{
|
||||
UserID: userID,
|
||||
Title: body.Title,
|
||||
Fingerprint: fingerprint,
|
||||
PublicKey: strings.TrimSpace(body.PublicKey),
|
||||
}
|
||||
if _, err := h.db.Insert(key); err != nil {
|
||||
jsonError(w, "key already exists or could not be saved", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(key)
|
||||
}
|
||||
|
||||
func (h *SSHKeyHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||
keyID, err := strconv.ParseInt(chi.URLParam(r, "keyID"), 10, 64)
|
||||
if err != nil {
|
||||
jsonError(w, "invalid key ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
n, err := h.db.Where("id = ? AND user_id = ?", keyID, userID).Delete(&models.SSHKey{})
|
||||
if err != nil || n == 0 {
|
||||
jsonError(w, "key not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func fingerprintMD5(pub ssh.PublicKey) string {
|
||||
hash := md5.Sum(pub.Marshal())
|
||||
parts := make([]string, len(hash))
|
||||
for i, b := range hash {
|
||||
parts[i] = fmt.Sprintf("%02x", b)
|
||||
}
|
||||
return strings.Join(parts, ":")
|
||||
}
|
||||
@@ -40,6 +40,30 @@ func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, staticFi
|
||||
prH := handlers.NewPRHandler(engine)
|
||||
pipeH := handlers.NewPipelineHandler(engine)
|
||||
wsH := handlers.NewWSHandler()
|
||||
gitH := handlers.NewGitHTTPHandler(engine, cfg)
|
||||
issueH := handlers.NewIssueHandler(engine)
|
||||
sshKeyH := handlers.NewSSHKeyHandler(engine)
|
||||
|
||||
// ── Git smart-HTTP transport ───────────────────────────────────────────────
|
||||
// These routes MUST be registered before the SPA catch-all and outside CSRF.
|
||||
// Git clients use HTTP Basic Auth, not the cookie/CSRF flow.
|
||||
r.Route("/{owner}/{repoGit}", func(r chi.Router) {
|
||||
// Only activate for paths ending in .git
|
||||
r.Use(func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
rg := chi.URLParam(req, "repoGit")
|
||||
if len(rg) < 5 || rg[len(rg)-4:] != ".git" {
|
||||
// Not a git URL — skip to the next router
|
||||
http.NotFound(w, req)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, req)
|
||||
})
|
||||
})
|
||||
r.Get("/info/refs", gitH.ServeGit)
|
||||
r.Post("/git-upload-pack", gitH.ServeGit)
|
||||
r.Post("/git-receive-pack", gitH.ServeGit)
|
||||
})
|
||||
|
||||
r.Route("/api/v1", func(r chi.Router) {
|
||||
|
||||
@@ -71,11 +95,18 @@ func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, staticFi
|
||||
|
||||
r.Get("/me", userH.Me)
|
||||
|
||||
// SSH key management
|
||||
r.Get("/user/keys", sshKeyH.List)
|
||||
r.With(csrf).Post("/user/keys", sshKeyH.Add)
|
||||
r.With(csrf).Delete("/user/keys/{keyID}", sshKeyH.Delete)
|
||||
|
||||
r.Route("/repos", func(r chi.Router) {
|
||||
r.Get("/", repoH.List)
|
||||
r.With(csrf).Post("/", repoH.Create)
|
||||
r.Route("/{owner}/{repo}", func(r chi.Router) {
|
||||
r.Get("/", repoH.Get)
|
||||
r.With(csrf).Patch("/", repoH.Update)
|
||||
r.With(csrf).Delete("/", repoH.Delete)
|
||||
r.Get("/tree", repoH.Tree)
|
||||
r.Get("/blob", repoH.Blob)
|
||||
r.Get("/commits", repoH.Commits)
|
||||
@@ -87,6 +118,13 @@ func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, staticFi
|
||||
r.With(csrf).Post("/{prID}/merge", prH.Merge)
|
||||
r.With(csrf).Post("/{prID}/close", prH.Close)
|
||||
})
|
||||
r.Route("/issues", func(r chi.Router) {
|
||||
r.Get("/", issueH.List)
|
||||
r.With(csrf).Post("/", issueH.Create)
|
||||
r.Get("/{issueNum}", issueH.Get)
|
||||
r.With(csrf).Post("/{issueNum}/close", issueH.Close)
|
||||
r.With(csrf).Post("/{issueNum}/reopen", issueH.Reopen)
|
||||
})
|
||||
r.Route("/pipelines", func(r chi.Router) {
|
||||
r.Get("/", pipeH.List)
|
||||
r.Get("/{runID}", pipeH.Get)
|
||||
|
||||
@@ -54,12 +54,15 @@ func IsEmpty(repoPath string) bool {
|
||||
}
|
||||
|
||||
func Init(path string) error {
|
||||
// git init --bare works even if the directory doesn't exist yet
|
||||
cmd := exec.Command("git", "init", "--bare", path)
|
||||
cmd.Env = []string{"GIT_TERMINAL_PROMPT=0", "HOME=/tmp"}
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("git init --bare: %w: %s", err, out)
|
||||
}
|
||||
// Allow pushes over HTTP (git http-backend checks this config key)
|
||||
cfg := exec.Command("git", "-C", path, "config", "http.receivepack", "true")
|
||||
cfg.Env = []string{"GIT_TERMINAL_PROMPT=0", "HOME=/tmp"}
|
||||
_ = cfg.Run()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type IssueState string
|
||||
|
||||
const (
|
||||
IssueStateOpen IssueState = "open"
|
||||
IssueStateClosed IssueState = "closed"
|
||||
)
|
||||
|
||||
type Issue struct {
|
||||
ID int64 `xorm:"'id' pk autoincr" json:"id"`
|
||||
RepoID int64 `xorm:"'repo_id' notnull index" json:"repoId"`
|
||||
AuthorID int64 `xorm:"'author_id' notnull index" json:"authorId"`
|
||||
Number int `xorm:"'number' notnull" json:"number"`
|
||||
Title string `xorm:"'title' notnull varchar(255)" json:"title"`
|
||||
Body string `xorm:"'body' text" json:"body"`
|
||||
State IssueState `xorm:"'state' default 'open' varchar(16)" json:"state"`
|
||||
CreatedAt time.Time `xorm:"'created_at' created" json:"createdAt"`
|
||||
UpdatedAt time.Time `xorm:"'updated_at' updated" json:"updatedAt"`
|
||||
}
|
||||
@@ -6,10 +6,15 @@ import (
|
||||
)
|
||||
|
||||
func Run(engine *xorm.Engine) error {
|
||||
return engine.Sync2(
|
||||
if err := engine.Sync2(
|
||||
&models.User{},
|
||||
&models.Repository{},
|
||||
&models.PullRequest{},
|
||||
&models.FederationActor{},
|
||||
)
|
||||
&models.Issue{},
|
||||
&models.SSHKey{},
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
return Run002(engine)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/forgeo/forgebucket/internal/models"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func Run002(engine *xorm.Engine) error {
|
||||
return engine.Sync2(
|
||||
&models.Issue{},
|
||||
&models.SSHKey{},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type SSHKey struct {
|
||||
ID int64 `xorm:"'id' pk autoincr" json:"id"`
|
||||
UserID int64 `xorm:"'user_id' notnull index" json:"userId"`
|
||||
Title string `xorm:"'title' notnull varchar(255)" json:"title"`
|
||||
Fingerprint string `xorm:"'fingerprint' notnull unique" json:"fingerprint"`
|
||||
PublicKey string `xorm:"'public_key' text notnull" json:"publicKey"`
|
||||
CreatedAt time.Time `xorm:"'created_at' created" json:"createdAt"`
|
||||
}
|
||||
Reference in New Issue
Block a user