# Conflicts:
#	models/issue.go
#	models/issue_comment.go
#	options/locale/locale_en-US.ini
#	public/js/index.js
#	templates/repo/issue/view_content/comments.tmpl
#	templates/repo/issue/view_content/sidebar.tmpl
This commit is contained in:
kolaente 2018-05-01 21:51:05 +02:00
commit 16533e9e2e
No known key found for this signature in database
GPG Key ID: F40E70337AB24C9B
25 changed files with 498 additions and 44 deletions

View File

@ -47,9 +47,10 @@ type Issue struct {
Ref string
DeadlineUnix util.TimeStamp `xorm:"INDEX"`
CreatedUnix util.TimeStamp `xorm:"INDEX created"`
UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
ClosedUnix util.TimeStamp `xorm:"INDEX"`
CreatedUnix util.TimeStamp `xorm:"INDEX created"`
UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
ClosedUnix util.TimeStamp `xorm:"INDEX"`
Attachments []*Attachment `xorm:"-"`
Comments []*Comment `xorm:"-"`
@ -79,6 +80,11 @@ func (issue *Issue) loadTotalTimes(e Engine) (err error) {
return nil
}
// IsOverdue checks if the issue is overdue
func (issue *Issue) IsOverdue() bool {
return util.TimeStampNow() >= issue.DeadlineUnix
}
func (issue *Issue) loadRepo(e Engine) (err error) {
if issue.Repo == nil {
issue.Repo, err = getRepositoryByID(e, issue.RepoID)
@ -348,6 +354,9 @@ func (issue *Issue) APIFormat() *api.Issue {
apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr()
}
}
if issue.DeadlineUnix != 0 {
apiIssue.Deadline = issue.DeadlineUnix.AsTimePtr()
}
return apiIssue
}
@ -1537,6 +1546,33 @@ func UpdateIssue(issue *Issue) error {
return updateIssue(x, issue)
}
// UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
func UpdateIssueDeadline(issue *Issue, deadlineUnix util.TimeStamp, doer *User) (err error) {
// if the deadline hasn't changed do nothing
if issue.DeadlineUnix == deadlineUnix {
return nil
}
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
// Update the deadline
if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
return err
}
// Make the comment
if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
return fmt.Errorf("createRemovedDueDateComment: %v", err)
}
return sess.Commit()
}
// Get Blocked By Dependencies, aka all issues this issue is blocked by.
func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*Issue, err error) {
return issueDeps, e.

View File

@ -60,6 +60,12 @@ const (
CommentTypeAddTimeManual
// Cancel a stopwatch for time tracking
CommentTypeCancelTracking
// Added a due date
CommentTypeAddedDeadline
// Modified the due date
CommentTypeModifiedDeadline
// Removed a due date
CommentTypeRemovedDeadline
// Dependency added
CommentTypeAddDependency
//Dependency removed
@ -508,6 +514,34 @@ func createAssigneeComment(e *xorm.Session, doer *User, repo *Repository, issue
})
}
func createDeadlineComment(e *xorm.Session, doer *User, issue *Issue, newDeadlineUnix util.TimeStamp) (*Comment, error) {
var content string
var commentType CommentType
// newDeadline = 0 means deleting
if newDeadlineUnix == 0 {
commentType = CommentTypeRemovedDeadline
content = issue.DeadlineUnix.Format("2006-01-02")
} else if issue.DeadlineUnix == 0 {
// Check if the new date was added or modified
// If the actual deadline is 0 => deadline added
commentType = CommentTypeAddedDeadline
content = newDeadlineUnix.Format("2006-01-02")
} else { // Otherwise modified
commentType = CommentTypeModifiedDeadline
content = newDeadlineUnix.Format("2006-01-02") + "|" + issue.DeadlineUnix.Format("2006-01-02")
}
return createComment(e, &CreateCommentOptions{
Type: commentType,
Doer: doer,
Repo: issue.Repo,
Issue: issue,
Content: content,
})
}
func createChangeTitleComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldTitle, newTitle string) (*Comment, error) {
return createComment(e, &CreateCommentOptions{
Type: CommentTypeChangeTitle,

View File

@ -207,6 +207,7 @@ func (pr *PullRequest) APIFormat() *api.PullRequest {
Base: apiBaseBranchInfo,
Head: apiHeadBranchInfo,
MergeBase: pr.MergeBase,
Deadline: apiIssue.Deadline,
Created: pr.Issue.CreatedUnix.AsTimePtr(),
Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
}

View File

@ -522,3 +522,13 @@ func (f *AddTimeManuallyForm) Validate(ctx *macaron.Context, errs binding.Errors
type SaveTopicForm struct {
Topics []string `binding:"topics;Required;"`
}
// DeadlineForm hold the validation rules for deadlines
type DeadlineForm struct {
DateString string `form:"date" binding:"Required;Size(10)"`
}
// Validate validates the fields
func (f *DeadlineForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

View File

@ -183,6 +183,9 @@ func NewFuncMap() []template.FuncMap {
"Printf": fmt.Sprintf,
"Escape": Escape,
"Sec2Time": models.SecToTime,
"ParseDeadline": func(deadline string) []string {
return strings.Split(deadline, "|")
},
}}
}

View File

@ -330,6 +330,7 @@ lookup_avatar_by_mail=Avatar anhand der E-Mail-Addresse suchen
federated_avatar_lookup=Suche nach föderierten Profilbildern
enable_custom_avatar=Benutzerdefiniertes Profilbild benutzen
choose_new_avatar=Neues Profilbild auswählen
update_avatar=Profilbild aktualisieren
delete_current_avatar=Aktuelles Profilbild löschen
uploaded_avatar_not_a_image=Die hochgeladene Datei ist kein Bild.
update_avatar_success=Dein Profilbild wurde geändert.
@ -416,9 +417,18 @@ access_token_deletion=Zugriffstoken löschen
twofa_is_enrolled=Für dein Konto ist die Zwei-Faktor-Authentifizierung <strong>eingeschaltet</strong>.
twofa_not_enrolled=Für dein Konto ist die Zwei-Faktor-Authentifizierung momentan nicht eingeschaltet.
twofa_disable=Zwei-Faktor-Authentifizierung deaktivieren
twofa_scratch_token_regenerate=Neues Einmalpasswort erstellen
twofa_scratch_token_regenerated=Dein Einmalpasswort ist %s. Bewahre es an einem sicheren Ort auf.
twofa_enroll=Zwei-Faktor-Authentifizierung aktivieren
twofa_disable_note=Du kannst die Zwei-Faktor-Authentifizierung auch wieder deaktivieren.
twofa_disable_desc=Wenn du die Zwei-Faktor-Authentifizierung deaktivierst, wird die Sicherheit deines Kontos verringert. Fortfahren?
twofa_disabled=Zwei-Faktor-Authentifizierung wurde deaktiviert.
scan_this_image=Scanne diese Grafik mit deiner Authentifizierungs-App:
or_enter_secret=Oder gib das Secret ein: %s
then_enter_passcode=Und gebe dann die angezeigte PIN der Anwendung ein:
passcode_invalid=Die PIN ist falsch. Probiere es erneut.
twofa_enrolled=Die Zwei-Faktor-Authentifizierung wurde für dein Konto aktiviert. Bewahre dein Einmalpasswort (%s) an einem sicheren Ort auf, da es nicht wieder angezeigt werden wird.
orgs_none=Du bist kein Mitglied in einer Organisation.

View File

@ -736,8 +736,22 @@ issues.add_time_minutes = Minutes
issues.add_time_sum_to_small = No time was entered.
issues.cancel_tracking = Cancel
issues.cancel_tracking_history = `cancelled time tracking %s`
issues.time_spent_total = Total time spent
issues.time_spent_total = Total Time Spent
issues.time_spent_from_all_authors = `Total Time Spent: %s`
issues.due_date = Due date
issues.invalid_due_date_format = "Due date format is invalid, must be 'yyyy-mm-dd'."
issues.error_modifying_due_date = "An error occured while modifying the due date."
issues.error_removing_due_date = "An error occured while remvoing the due date."
issues.due_date_form = "Due date, format yyyy-mm-dd"
issues.due_date_form_add = "Add due date"
issues.due_date_form_update = "Update due date"
issues.due_date_form_remove = "Remove due date"
issues.due_date_not_writer = "You need to have at least write access to this repository in order to update the due date for this issue."
issues.due_date_not_set = "No due date set."
issues.due_date_added = "added the due date %s %s"
issues.due_date_modified = "modified the due date to %s from %s %s"
issues.due_date_remove = "removed the due date %s %s"
issues.due_date_overdue = "Overdue"
issues.dependency.title = Dependencies
issues.dependency.issue_no_dependencies = This issue currently doesn't have any dependencies.
issues.dependency.pr_no_dependencies = This pull request currently doesn't have any dependencies.

View File

@ -18,6 +18,7 @@ template=Шаблон
language=Язык
notifications=Уведомления
create_new=Создать…
user_profile_and_more=Профиль и настройки...
signed_in_as=Вы вошли как
enable_javascript=Пожалуйста, включите JavaScript.
@ -79,8 +80,10 @@ repo_path=Путь корня репозитория
repo_path_helper=Все удаленные Git репозиториии будут сохранены в этот каталог.
lfs_path=Корневой путь Git LFS
lfs_path_helper=В этой папке будут храниться файлы Git LFS. Оставьте пустым, чтобы отключить LFS.
domain=Домен SSH сервера
ssh_port=Порт SSH сервера
ssh_port_helper=Номер порта, который использует SSH сервер. Оставьте пустым, чтобы отключить SSH.
app_url=Базовый URL-адрес Gitea
log_root_path=Путь к журналу
optional_title=Расширенные настройки
@ -90,14 +93,31 @@ smtp_from=Отправлять Email от имени
mailer_user=SMTP логин
mailer_password=SMTP пароль
mail_notify=Разрешить почтовые уведомления
server_service_title=Сервер и настройки внешних служб
disable_gravatar=Отключить Gravatar
federated_avatar_lookup_popup=Включите поиск федеративного аватара для использования службы с открытым исходным кодом на основе libravatar.
openid_signin=Включение входа через OpenID
openid_signin_popup=Включение входа через OpenID.
openid_signup=Включить саморегистрацию OpenID
openid_signup_popup=Включить саморегистрацию OpenID.
enable_captcha=Включить CAPTCHA
enable_captcha_popup=Запрашивать капчу при регистрации пользователя.
require_sign_in_view=Требовать авторизации для просмотра страниц
admin_title=Настройки учётной записи администратора
admin_name=Логин администратора
admin_password=Пароль
confirm_password=Подтвердить пароль
admin_email=Адрес эл. почты
install_btn_confirm=Установить Gitea
test_git_failed=Не удалось проверить 'git' команду: %v
invalid_db_setting=Недопустимые параметры настройки базы данных: %v
invalid_repo_path=Недопустимый путь к корню репозитория: %v
save_config_failed=Не удалось сохранить конфигурацию: %v
invalid_admin_setting=Указан недопустимый параметр учетной записи администратора: %v
install_success=Добро пожаловать! Благодарим вас за выбор Gitea, пользуйтесь с удовольствием!
invalid_log_root_path=Недопустимый путь для логов: %v
default_enable_timetracking=Включение отслеживания времени по умолчанию
no_reply_address=Скрытый почтовый домен
[home]
uname_holder=Имя пользователя / Email
@ -210,7 +230,11 @@ team_name_been_taken=Название команды уже занято.
email_been_used=Этот адрес электронной почты уже используется.
openid_been_used=Адрес OpenID '%s' уже используется.
username_password_incorrect=Неверное имя пользователя или пароль.
enterred_invalid_repo_name=Введенное вами имя репозитория неверно.
enterred_invalid_owner_name=Имя нового владельца недоступно.
enterred_invalid_password=Введенный пароль неверный.
user_not_exist=Пользователь не существует.
cannot_add_org_to_team=Организацию нельзя добавить в качестве члена команды.
auth_failed=Ошибка аутентификации: %v
@ -235,32 +259,51 @@ security=Безопасность
avatar=Аватар
ssh_gpg_keys=SSH / GPG ключи
social=Учетные записи в соцсетях
orgs=Управление организациями
repos=Репозитории
delete=Удалить аккаунт
twofa=Двухфакторная аутентификация
account_link=Привязанные аккаунты
organization=Организации
uid=UID
public_profile=Открытый профиль
profile_desc=Ваш адрес электронной почты будет использован для уведомлений и других операций.
password_username_disabled=Нелокальным пользователям запрещено изменение их имени пользователя. Для получения более подробной информации обратитесь к администратору сайта.
full_name=ФИО
website=Веб-сайт
location=Местоположение
update_profile=Обновить профиль
update_profile_success=Ваш профиль успешно обновлен.
change_username=Ваше имя пользователя было изменено.
continue=Далее
cancel=Отмена
federated_avatar_lookup=Найти внешний аватар
enable_custom_avatar=Включить собственный аватар
choose_new_avatar=Выбрать новый аватар
update_avatar=Обновить аватар
delete_current_avatar=Удалить текущий аватар
uploaded_avatar_not_a_image=Загружаемый файл не является изображением.
update_avatar_success=Ваш аватар был изменен.
change_password=Обновить пароль
old_password=Текущий пароль
new_password=Новый пароль
retype_new_password=Подтверждение нового пароля
password_incorrect=Текущий пароль неправильный.
password_change_disabled=Нелокальные аккаунты не могут изменить пароль через Gitea.
emails=Email адреса
email_desc=Ваш основной адрес электронной почты будет использован для уведомлений и других операций.
primary=Основной
delete_email=Удалить
email_deletion=Удалить адрес электронной почты
email_deletion_desc=Адрес электронной почты и вся связанная с ним информация будет удалена из вашего аккаунта. Коммиты, сделанные от имени этого адреса электронной почты, не будут изменены. Продолжить?
add_new_email=Добавить новый адрес электронной почты
add_email=Добавить новый адрес электронной почты
add_openid=Добавить адрес OpenID
add_email_confirmation_sent=Письмо для подтверждения было отправлено на '%s'. Пожалуйста, проверьте ваш почтовый ящик в течение %s, чтобы завершить процесс подтверждения.
manage_ssh_keys=Управление SSH ключами
manage_gpg_keys=Управление GPG ключами
@ -269,10 +312,16 @@ ssh_helper=<strong>Нужна помощь?</strong> Ознакомьтесь с
gpg_helper=<strong>Нужна помощь?</strong> Взгляните на руководство GitHub <a href="%s"> по GPG</a>.
add_new_key=Добавить SSH ключ
add_new_gpg_key=Добавить GPG ключ
gpg_key_id_used=Публичный GPG ключ с таким же идентификатором уже существует.
subkeys=Подключи
key_id=ИД ключа
key_name=Имя ключа
key_content=Содержимое
add_key_success=SSH ключ '%s' добавлен.
add_gpg_key_success=GPG ключ '%s' добавлен.
delete_key=Удалить
ssh_key_deletion_success=SSH ключ был удален.
gpg_key_deletion_success=GPG ключ был удален.
add_on=Добавлено
valid_until=Действителен до
valid_forever=Действителен навсегда
@ -284,16 +333,23 @@ key_state_desc=Этот ключ использовался в течение п
token_state_desc=Этот токен использовался в течение последних 7 дней
show_openid=Показывать в профиле
hide_openid=Скрыть из профиля
ssh_disabled=SSH отключён
manage_social=Управление привязанными учетными записями в соцсетях
unbind=Удалить связь
unbind_success=Связанная внешняя учётная запись была удалена.
generate_new_token=Создать новый токен
token_name=Имя токена
generate_token=Генерировать токен
delete_token=Удалить
twofa_desc=Двухфакторная проверка подлинности повышает уровень безопасности вашей учётной записи.
twofa_is_enrolled=Ваша учётная запись в настоящее время <strong>использует</strong> двухфакторную аутентификацию.
twofa_not_enrolled=Ваша учётная запись в настоящее время не использует двухфакторную аутентификацию.
twofa_disable=Отключить двухфакторную аутентификацию
twofa_scratch_token_regenerate=Пересоздать scratch-токен
twofa_enroll=Включить двухфакторную аутентификацию
twofa_disabled=Двухфакторная аутентификация выключена.
scan_this_image=Сканируйте это изображение вашим приложением для двуфакторной аутентификации:
or_enter_secret=Или введите кодовое слово: %s
@ -313,10 +369,16 @@ fork_repo=Форкнуть репозиторий
fork_from=Форк от
repo_desc=Описание
repo_lang=Язык
repo_gitignore_helper=Выберите шаблон .gitignore.
license=Лицензия
license_helper=Выберите файл лицензии.
readme=README
readme_helper=Выберите шаблон README.
create_repo=Создать репозиторий
default_branch=Ветка по умолчанию
mirror_prune=Очистить
mirror_interval=Интервал зеркалирования (допустимы единицы времени 'h', 'm', 's')
mirror_interval_invalid=Недопустимый интервал зеркалирования.
watchers=Наблюдатели
stargazers=Звездочеты
forks=Форки
@ -329,18 +391,25 @@ form.name_reserved=Имя репозитория '%s' зарезервирова
migrate_type=Тип миграции
migrate_type_helper=Этот репозиторий будет <span class="text blue">зеркалом</span>
migrate_repo=Перенос репозитория
migrate.clone_local_path=или путь к локальному серверу
migrate.permission_denied=У вас нет прав на импорт локальных репозиториев.
migrate.invalid_local_path=Недопустимый локальный путь. Возможно он не существует или не является папкой.
migrate.failed=Миграция не удалась: %v
migrate.lfs_mirror_unsupported=Зеркалирование LFS объектов не поддерживается - используйте 'git lfs fetch --all' и 'git lfs push --all' вручную.
mirror_from=зеркало из
forked_from=форкнуто от
fork_from_self=Вы не можете форкнуть репозиторий, так как вы уже его владелец.
copy_link=Скопировать
copy_link_success=Ссылка была скопирована
copy_link_error=Нажмите ⌘-C или Ctrl-C для копирования
copied=Успешно скопировано
unwatch=Перестать следить
watch=Следить
unstar=Убрать из избранного
star=В избранное
fork=Форкнуть
download_archive=Скачать репозиторий
no_desc=Нет описания
quick_guide=Краткое руководство

View File

@ -79,6 +79,7 @@ repo_path=Кореневий шлях репозиторія
repo_path_helper=Всі вилучені Git репозиторії будуть збережені в цей каталог.
lfs_path=Кореневої шлях Git LFS
lfs_path_helper=У цій папці будуть зберігатися файли Git LFS. Залиште порожнім, щоб відключити LFS.
domain=Домен SSH сервера
ssh_port=Порт SSH сервера
ssh_port_helper=Номер порту, який використовує SSH сервер. Залиште порожнім, щоб відключити SSH.
app_url=Базова URL-адреса Gitea

File diff suppressed because one or more lines are too long

View File

@ -2195,6 +2195,18 @@ function initTopicbar() {
},
});
}
function toggleDuedateForm() {
$('#add_deadline_form').fadeToggle(150);
}
function deleteDueDate(url) {
$.post(url, {
'_csrf': csrf,
},function( data ) {
window.location.reload();
});
}
function deleteDependencyModal(id, type) {
$('.remove-dependency')
.modal({

View File

@ -1545,6 +1545,9 @@
margin-top: -5px;
margin-right: 5px;
}
.overdue{
color: red;
}
}
}
}

View File

@ -5579,6 +5579,13 @@
"type": "string",
"x-go-name": "Assignee"
},
"assignees": {
"type": "array",
"items": {
"type": "string"
},
"x-go-name": "Assignees"
},
"body": {
"type": "string",
"x-go-name": "Body"
@ -5587,6 +5594,11 @@
"type": "boolean",
"x-go-name": "Closed"
},
"due_date": {
"type": "string",
"format": "date-time",
"x-go-name": "Deadline"
},
"labels": {
"description": "list of label ids",
"type": "array",
@ -5715,6 +5727,13 @@
"type": "string",
"x-go-name": "Assignee"
},
"assignees": {
"type": "array",
"items": {
"type": "string"
},
"x-go-name": "Assignees"
},
"base": {
"type": "string",
"x-go-name": "Base"
@ -5723,6 +5742,11 @@
"type": "string",
"x-go-name": "Body"
},
"due_date": {
"type": "string",
"format": "date-time",
"x-go-name": "Deadline"
},
"head": {
"type": "string",
"x-go-name": "Head"
@ -6024,10 +6048,22 @@
"type": "string",
"x-go-name": "Assignee"
},
"assignees": {
"type": "array",
"items": {
"type": "string"
},
"x-go-name": "Assignees"
},
"body": {
"type": "string",
"x-go-name": "Body"
},
"due_date": {
"type": "string",
"format": "date-time",
"x-go-name": "Deadline"
},
"milestone": {
"type": "integer",
"format": "int64",
@ -6114,10 +6150,22 @@
"type": "string",
"x-go-name": "Assignee"
},
"assignees": {
"type": "array",
"items": {
"type": "string"
},
"x-go-name": "Assignees"
},
"body": {
"type": "string",
"x-go-name": "Body"
},
"due_date": {
"type": "string",
"format": "date-time",
"x-go-name": "Deadline"
},
"labels": {
"type": "array",
"items": {
@ -6367,10 +6415,22 @@
"assignee": {
"$ref": "#/definitions/User"
},
"assignees": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
},
"x-go-name": "Assignees"
},
"body": {
"type": "string",
"x-go-name": "Body"
},
"closed_at": {
"type": "string",
"format": "date-time",
"x-go-name": "Closed"
},
"comments": {
"type": "integer",
"format": "int64",
@ -6381,6 +6441,11 @@
"format": "date-time",
"x-go-name": "Created"
},
"due_date": {
"type": "string",
"format": "date-time",
"x-go-name": "Deadline"
},
"id": {
"type": "integer",
"format": "int64",
@ -6778,6 +6843,13 @@
"assignee": {
"$ref": "#/definitions/User"
},
"assignees": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
},
"x-go-name": "Assignees"
},
"base": {
"$ref": "#/definitions/PRBranchInfo"
},
@ -6785,6 +6857,11 @@
"type": "string",
"x-go-name": "Body"
},
"closed_at": {
"type": "string",
"format": "date-time",
"x-go-name": "Closed"
},
"comments": {
"type": "integer",
"format": "int64",
@ -6799,6 +6876,11 @@
"type": "string",
"x-go-name": "DiffURL"
},
"due_date": {
"type": "string",
"format": "date-time",
"x-go-name": "Deadline"
},
"head": {
"$ref": "#/definitions/PRBranchInfo"
},

View File

@ -164,12 +164,19 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) {
// responses:
// "201":
// "$ref": "#/responses/Issue"
var deadlineUnix util.TimeStamp
if form.Deadline != nil {
deadlineUnix = util.TimeStamp(form.Deadline.Unix())
}
issue := &models.Issue{
RepoID: ctx.Repo.Repository.ID,
Title: form.Title,
PosterID: ctx.User.ID,
Poster: ctx.User,
Content: form.Body,
RepoID: ctx.Repo.Repository.ID,
Title: form.Title,
PosterID: ctx.User.ID,
Poster: ctx.User,
Content: form.Body,
DeadlineUnix: deadlineUnix,
}
if ctx.Repo.IsWriter() {
@ -270,6 +277,16 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) {
issue.Content = *form.Body
}
var deadlineUnix util.TimeStamp
if form.Deadline != nil && !form.Deadline.IsZero() {
deadlineUnix = util.TimeStamp(form.Deadline.Unix())
}
if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil {
ctx.Error(500, "UpdateIssueDeadline", err)
return
}
if ctx.Repo.IsWriter() && form.Assignee != nil &&
(issue.Assignee == nil || issue.Assignee.LowerName != strings.ToLower(*form.Assignee)) {
if len(*form.Assignee) == 0 {

View File

@ -14,6 +14,7 @@ import (
"code.gitea.io/gitea/modules/auth"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/util"
api "code.gitea.io/sdk/gitea"
)
@ -237,16 +238,22 @@ func CreatePullRequest(ctx *context.APIContext, form api.CreatePullRequestOption
return
}
var deadlineUnix util.TimeStamp
if form.Deadline != nil {
deadlineUnix = util.TimeStamp(form.Deadline.Unix())
}
prIssue := &models.Issue{
RepoID: repo.ID,
Index: repo.NextIssueIndex(),
Title: form.Title,
PosterID: ctx.User.ID,
Poster: ctx.User,
MilestoneID: milestoneID,
AssigneeID: assigneeID,
IsPull: true,
Content: form.Body,
RepoID: repo.ID,
Index: repo.NextIssueIndex(),
Title: form.Title,
PosterID: ctx.User.ID,
Poster: ctx.User,
MilestoneID: milestoneID,
AssigneeID: assigneeID,
IsPull: true,
Content: form.Body,
DeadlineUnix: deadlineUnix,
}
pr := &models.PullRequest{
HeadRepoID: headRepo.ID,
@ -329,6 +336,16 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) {
issue.Content = form.Body
}
var deadlineUnix util.TimeStamp
if form.Deadline != nil && !form.Deadline.IsZero() {
deadlineUnix = util.TimeStamp(form.Deadline.Unix())
}
if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil {
ctx.Error(500, "UpdateIssueDeadline", err)
return
}
if ctx.Repo.IsWriter() && len(form.Assignee) > 0 &&
(issue.Assignee == nil || issue.Assignee.LowerName != strings.ToLower(form.Assignee)) {
if len(form.Assignee) == 0 {

View File

@ -1499,3 +1499,51 @@ func ChangeCommentReaction(ctx *context.Context, form auth.ReactionForm) {
"html": html,
})
}
// UpdateDeadline adds or updates a deadline
func UpdateDeadline(ctx *context.Context, form auth.DeadlineForm) {
issue := GetActionIssue(ctx)
if ctx.Written() {
return
}
if ctx.HasError() {
ctx.ServerError("ChangeIssueDeadline", errors.New(ctx.GetErrMsg()))
return
}
// Make unix of deadline string
deadline, err := time.ParseInLocation("2006-01-02", form.DateString, time.Local)
if err != nil {
ctx.Flash.Error(ctx.Tr("repo.issues.invalid_due_date_format"))
ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index))
return
}
if err = models.UpdateIssueDeadline(issue, util.TimeStamp(deadline.Unix()), ctx.User); err != nil {
ctx.Flash.Error(ctx.Tr("repo.issues.error_modifying_due_date"))
}
ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index))
return
}
// RemoveDeadline removes a deadline
func RemoveDeadline(ctx *context.Context) {
issue := GetActionIssue(ctx)
if ctx.Written() {
return
}
if ctx.HasError() {
ctx.ServerError("RemoveIssueDeadline", errors.New(ctx.GetErrMsg()))
return
}
if err := models.UpdateIssueDeadline(issue, 0, ctx.User); err != nil {
ctx.Flash.Error(ctx.Tr("repo.issues.error_removing_due_date"))
}
ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index))
return
}

View File

@ -500,6 +500,8 @@ func RegisterRoutes(m *macaron.Macaron) {
})
})
m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction)
m.Post("/deadline/update", reqRepoWriter, bindIgnErr(auth.DeadlineForm{}), repo.UpdateDeadline)
m.Post("/deadline/delete", reqRepoWriter, repo.RemoveDeadline)
})
m.Post("/labels", reqRepoWriter, repo.UpdateIssueLabel)

View File

@ -216,6 +216,10 @@
<span class="octicon octicon-milestone"></span> {{.Milestone.Name}}
</a>
{{end}}
{{if ne .DeadlineUnix 0}}
<span class="octicon octicon-calendar"></span>
<span{{if .IsOverdue}} class="overdue"{{end}}>{{.DeadlineUnix.FormatShort}}</span>
{{end}}
{{if .Assignee}}
<a class="ui right assignee poping up" href="{{.Assignee.HomeLink}}" data-content="{{.Assignee.Name}}" data-variation="inverted" data-position="left center">
<img class="ui avatar image" src="{{.Assignee.RelAvatarLink}}">

View File

@ -56,7 +56,7 @@
{{else}}
<span class="octicon octicon-calendar"></span>
{{if .DeadlineString}}
<span {{if .IsOverDue}}class="overdue"{{end}}>{{.DeadlineString}}</span>
<span {{if .IsOverdue}}class="overdue"{{end}}>{{.DeadlineString}}</span>
{{else}}
{{$.i18n.Tr "repo.milestones.no_due_date"}}
{{end}}

View File

@ -1,7 +1,7 @@
{{range .Issue.Comments}}
{{ $createdStr:= TimeSinceUnix .CreatedUnix $.Lang }}
<!-- 0 = COMMENT, 1 = REOPEN, 2 = CLOSE, 3 = ISSUE_REF, 4 = COMMIT_REF, 5 = COMMENT_REF, 6 = PULL_REF, 7 = COMMENT_LABEL, 12 = START_TRACKING, 13 = STOP_TRACKING, 14 = ADD_TIME_MANUAL, 15 = CANCEL_TIME_TRACKING, 16 = ADD_DEPENDENCY, 17 = REMOVE_DEPENDENCY -->
<!-- 0 = COMMENT, 1 = REOPEN, 2 = CLOSE, 3 = ISSUE_REF, 4 = COMMIT_REF, 5 = COMMENT_REF, 6 = PULL_REF, 7 = COMMENT_LABEL, 12 = START_TRACKING, 13 = STOP_TRACKING, 14 = ADD_TIME_MANUAL, 16 = ADDED_DEADLINE, 17 = MODIFIED_DEADLINE, 18 = REMOVED_DEADLINE, 19 = ADD_DEPENDENCY, 20 = REMOVE_DEPENDENCY -->
{{if eq .Type 0}}
<div class="comment" id="{{.HashTag}}">
<a class="avatar" {{if gt .Poster.ID 0}}href="{{.Poster.HomeLink}}"{{end}}>
@ -188,6 +188,36 @@
</a>
<span class="text grey"><a href="{{.Poster.HomeLink}}">{{.Poster.Name}}</a> {{$.i18n.Tr "repo.issues.cancel_tracking_history" $createdStr | Safe}}</span>
</div>
{{else if eq .Type 16}}
<div class="event">
<span class="octicon octicon-primitive-dot"></span>
<a class="ui avatar image" href="{{.Poster.HomeLink}}">
<img src="{{.Poster.RelAvatarLink}}">
</a>
<span class="text grey"><a href="{{.Poster.HomeLink}}">{{.Poster.Name}}</a>
{{$.i18n.Tr "repo.issues.due_date_added" .Content $createdStr | Safe}}
</span>
</div>
{{else if eq .Type 17}}
<div class="event">
<span class="octicon octicon-primitive-dot"></span>
<a class="ui avatar image" href="{{.Poster.HomeLink}}">
<img src="{{.Poster.RelAvatarLink}}">
</a>
<span class="text grey"><a href="{{.Poster.HomeLink}}">{{.Poster.Name}}</a>
{{$.i18n.Tr "repo.issues.due_date_modified" (.Content | ParseDeadline) $createdStr | Safe}}
</span>
</div>
{{else if eq .Type 18}}
<div class="event">
<span class="octicon octicon-primitive-dot"></span>
<a class="ui avatar image" href="{{.Poster.HomeLink}}">
<img src="{{.Poster.RelAvatarLink}}">
</a>
<span class="text grey"><a href="{{.Poster.HomeLink}}">{{.Poster.Name}}</a>
{{$.i18n.Tr "repo.issues.due_date_remove" .Content $createdStr | Safe}}
</span>
</div>
{{else if eq .Type 16}}
<div class="event">
<span class="octicon octicon-primitive-dot"></span>

View File

@ -192,6 +192,44 @@
{{end}}
{{end}}
<div class="ui divider"></div>
<span class="text"><strong>{{.i18n.Tr "repo.issues.due_date"}}</strong></span>
{{if gt .Issue.DeadlineUnix 0}}
<p>
<span class="octicon octicon-calendar"></span>
{{.Issue.DeadlineUnix.FormatShort}}
{{if .Issue.IsOverdue}}
<span style="color: red;">{{.i18n.Tr "repo.issues.due_date_overdue"}}</span>
{{end}}
{{if and .IsSigned .IsRepositoryWriter}}
<br/>
<a style="cursor:pointer;" onclick="toggleDuedateForm();"><i class="edit icon"></i>Edit</a> -
<a style="cursor:pointer;" onclick="deleteDueDate('{{$.RepoLink}}/issues/{{.Issue.Index}}/deadline/delete');"><i class="remove icon"></i>Remove</a>
{{end}}
</p>
{{else}}
<p><i>{{.i18n.Tr "repo.issues.due_date_not_set"}}</i></p>
{{end}}
{{if and .IsSigned .IsRepositoryWriter}}
<form method="POST"{{if gt .Issue.DeadlineUnix 0}}style="display: none;"{{end}}} id="add_deadline_form" action="{{$.RepoLink}}/issues/{{.Issue.Index}}/deadline/update" class="ui action input fluid">
{{$.CsrfTokenHtml}}
<div class="ui fluid action input">
<input required placeholder="{{.i18n.Tr "repo.issues.due_date_form"}}" {{if gt .Issue.DeadlineUnix 0}}value="{{.Issue.DeadlineUnix.Format "2006-01-02"}}"{{end}} type="date" name="date" style="min-width: 13.9rem;border-radius: 4px 0 0 4px;border-right: 0;white-space: nowrap;">
<button class="ui green icon button">
{{if gt .Issue.DeadlineUnix 0}}
<i class="edit icon"></i>
{{else}}
<i class="plus icon"></i>
{{end}}
</button>
</div>
</form>
{{end}}
</div>
</div>
{{if .Repository.IsDependenciesEnabled}}
<div class="ui divider"></div>

View File

@ -35,7 +35,7 @@ func (c *Client) ListReleaseAttachments(user, repo string, release int64) ([]*At
return attachments, err
}
// ListReleaseAttachments list release's attachments
// GetReleaseAttachment returns the requested attachment
func (c *Client) GetReleaseAttachment(user, repo string, release int64, id int64) (*Attachment, error) {
a := new(Attachment)
err := c.getParsedResponse("GET",

View File

@ -39,6 +39,7 @@ type Issue struct {
Labels []*Label `json:"labels"`
Milestone *Milestone `json:"milestone"`
Assignee *User `json:"assignee"`
Assignees []*User `json:"assignees"`
// Whether the issue is open or closed
//
// type: string
@ -49,6 +50,10 @@ type Issue struct {
Created time.Time `json:"created_at"`
// swagger:strfmt date-time
Updated time.Time `json:"updated_at"`
// swagger:strfmt date-time
Closed *time.Time `json:"closed_at"`
// swagger:strfmt date-time
Deadline *time.Time `json:"due_date"`
PullRequest *PullRequestMeta `json:"pull_request"`
}
@ -89,7 +94,10 @@ type CreateIssueOption struct {
Title string `json:"title" binding:"Required"`
Body string `json:"body"`
// username of assignee
Assignee string `json:"assignee"`
Assignee string `json:"assignee"`
Assignees []string `json:"assignees"`
// swagger:strfmt date-time
Deadline *time.Time `json:"due_date"`
// milestone id
Milestone int64 `json:"milestone"`
// list of label ids
@ -110,11 +118,14 @@ func (c *Client) CreateIssue(owner, repo string, opt CreateIssueOption) (*Issue,
// EditIssueOption options for editing an issue
type EditIssueOption struct {
Title string `json:"title"`
Body *string `json:"body"`
Assignee *string `json:"assignee"`
Milestone *int64 `json:"milestone"`
State *string `json:"state"`
Title string `json:"title"`
Body *string `json:"body"`
Assignee *string `json:"assignee"`
Assignees []string `json:"assignees"`
Milestone *int64 `json:"milestone"`
State *string `json:"state"`
// swagger:strfmt date-time
Deadline *time.Time `json:"due_date"`
}
// EditIssue modify an existing issue for a given repository

View File

@ -22,6 +22,7 @@ type PullRequest struct {
Labels []*Label `json:"labels"`
Milestone *Milestone `json:"milestone"`
Assignee *User `json:"assignee"`
Assignees []*User `json:"assignees"`
State StateType `json:"state"`
Comments int `json:"comments"`
@ -40,10 +41,15 @@ type PullRequest struct {
Head *PRBranchInfo `json:"head"`
MergeBase string `json:"merge_base"`
// swagger:strfmt date-time
Deadline *time.Time `json:"due_date"`
// swagger:strfmt date-time
Created *time.Time `json:"created_at"`
// swagger:strfmt date-time
Updated *time.Time `json:"updated_at"`
// swagger:strfmt date-time
Closed *time.Time `json:"closed_at"`
}
// PRBranchInfo information about a branch
@ -79,13 +85,16 @@ func (c *Client) GetPullRequest(owner, repo string, index int64) (*PullRequest,
// CreatePullRequestOption options when creating a pull request
type CreatePullRequestOption struct {
Head string `json:"head" binding:"Required"`
Base string `json:"base" binding:"Required"`
Title string `json:"title" binding:"Required"`
Body string `json:"body"`
Assignee string `json:"assignee"`
Milestone int64 `json:"milestone"`
Labels []int64 `json:"labels"`
Head string `json:"head" binding:"Required"`
Base string `json:"base" binding:"Required"`
Title string `json:"title" binding:"Required"`
Body string `json:"body"`
Assignee string `json:"assignee"`
Assignees []string `json:"assignees"`
Milestone int64 `json:"milestone"`
Labels []int64 `json:"labels"`
// swagger:strfmt date-time
Deadline *time.Time `json:"due_date"`
}
// CreatePullRequest create pull request with options
@ -101,12 +110,15 @@ func (c *Client) CreatePullRequest(owner, repo string, opt CreatePullRequestOpti
// EditPullRequestOption options when modify pull request
type EditPullRequestOption struct {
Title string `json:"title"`
Body string `json:"body"`
Assignee string `json:"assignee"`
Milestone int64 `json:"milestone"`
Labels []int64 `json:"labels"`
State *string `json:"state"`
Title string `json:"title"`
Body string `json:"body"`
Assignee string `json:"assignee"`
Assignees []string `json:"assignees"`
Milestone int64 `json:"milestone"`
Labels []int64 `json:"labels"`
State *string `json:"state"`
// swagger:strfmt date-time
Deadline *time.Time `json:"due_date"`
}
// EditPullRequest modify pull request with PR id and options

6
vendor/vendor.json vendored
View File

@ -9,10 +9,10 @@
"revisionTime": "2018-04-21T01:08:19Z"
},
{
"checksumSHA1": "PWaIU7g1YSkETxka2DIS1EYsPK0=",
"checksumSHA1": "xXzi8Xx7HA3M0z3lR/1wr1Vz1fc=",
"path": "code.gitea.io/sdk/gitea",
"revision": "cdbef997666132599cc92dc22aa94de3db04adeb",
"revisionTime": "2018-03-02T14:48:43Z"
"revision": "142acef5ce79f78585afcce31748af46c72a3dea",
"revisionTime": "2018-04-17T00:54:29Z"
},
{
"checksumSHA1": "bOODD4Gbw3GfcuQPU2dI40crxxk=",