From c6366089df8390bc1f017006caaf4d4c69825880 Mon Sep 17 00:00:00 2001 From: 6543 Date: Mon, 13 Nov 2023 23:30:24 +0100 Subject: [PATCH 001/753] Dont leak private users via extensions (#28023) --- routers/web/user/home.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/routers/web/user/home.go b/routers/web/user/home.go index 8b9a4cd224..db3778d9e1 100644 --- a/routers/web/user/home.go +++ b/routers/web/user/home.go @@ -822,6 +822,11 @@ func UsernameSubRoute(ctx *context.Context) { reloadParam := func(suffix string) (success bool) { ctx.SetParams("username", strings.TrimSuffix(username, suffix)) context_service.UserAssignmentWeb()(ctx) + // check view permissions + if !user_model.IsUserVisibleToViewer(ctx, ctx.ContextUser, ctx.Doer) { + ctx.NotFound("user", fmt.Errorf(ctx.ContextUser.Name)) + return false + } return !ctx.Written() } switch { From 60522fc96f1fa4675e95010e4b1535e0eac21910 Mon Sep 17 00:00:00 2001 From: Danila Fominykh Date: Mon, 13 Nov 2023 20:38:50 -0300 Subject: [PATCH 002/753] packages: Calculate package size quota using package creator ID instead of owner ID (#28007) Changed behavior to calculate package quota limit using package `creator ID` instead of `owner ID`. Currently, users are allowed to create an unlimited number of organizations, each of which has its own package limit quota, resulting in the ability for users to have unlimited package space in different organization scopes. This fix will calculate package quota based on `package version creator ID` instead of `package version owner ID` (which might be organization), so that users are not allowed to take more space than configured package settings. Also, there is a side case in which users can publish packages to a specific package version, initially published by different user, taking that user package size quota. Version in fix should be better because the total amount of space is limited to the quota for users sharing the same organization scope. --- models/packages/package_file.go | 12 ++++++++++++ services/packages/packages.go | 4 +--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/models/packages/package_file.go b/models/packages/package_file.go index 1c2c9ac072..a2ddae7325 100644 --- a/models/packages/package_file.go +++ b/models/packages/package_file.go @@ -230,3 +230,15 @@ func CalculateFileSize(ctx context.Context, opts *PackageFileSearchOptions) (int Join("INNER", "package_blob", "package_blob.id = package_file.blob_id"). SumInt(new(PackageBlob), "size") } + +// CalculateCreatorPackageQuota sums up all blob sizes related to package +// version creator id. +// It does NOT respect the deduplication of blobs. +func CalculateCreatorPackageQuota(ctx context.Context, creatorID int64) (int64, error) { + return db.GetEngine(ctx). + Table("package_version"). + Where(builder.Eq{"creator_id": creatorID}). + Join("INNER", "package_file", "package_version.id = package_file.version_id"). + Join("INNER", "package_blob", "package_blob.id = package_file.blob_id"). + SumInt(new(PackageBlob), "size") +} diff --git a/services/packages/packages.go b/services/packages/packages.go index 56d5cc04de..294ee6cc1a 100644 --- a/services/packages/packages.go +++ b/services/packages/packages.go @@ -401,9 +401,7 @@ func CheckSizeQuotaExceeded(ctx context.Context, doer, owner *user_model.User, p } if setting.Packages.LimitTotalOwnerSize > -1 { - totalSize, err := packages_model.CalculateFileSize(ctx, &packages_model.PackageFileSearchOptions{ - OwnerID: owner.ID, - }) + totalSize, err := packages_model.CalculateCreatorPackageQuota(ctx, doer.ID) if err != nil { log.Error("CalculateFileSize failed: %v", err) return err From f586937297d6d77d0c4b1fe877154d7f39763429 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Tue, 14 Nov 2023 00:23:48 +0000 Subject: [PATCH 003/753] [skip ci] Updated translations via Crowdin --- options/locale/locale_ru-RU.ini | 89 ++++++++++++++++++++++----------- 1 file changed, 61 insertions(+), 28 deletions(-) diff --git a/options/locale/locale_ru-RU.ini b/options/locale/locale_ru-RU.ini index 3a560eba1d..aad2d86b83 100644 --- a/options/locale/locale_ru-RU.ini +++ b/options/locale/locale_ru-RU.ini @@ -163,7 +163,7 @@ buttons.code.tooltip=Добавить код buttons.link.tooltip=Добавить ссылку buttons.list.unordered.tooltip=Добавить маркированный список buttons.list.ordered.tooltip=Добавить нумерованный список -buttons.list.task.tooltip=Добавить список задач +buttons.list.task.tooltip=Добавить список заданий buttons.mention.tooltip=Упомянуть пользователя или команду buttons.ref.tooltip=Сослаться на задачу или запрос на слияние buttons.switch_to_legacy.tooltip=Использовать старый редактор @@ -937,6 +937,7 @@ fork_from=Форк от already_forked=Вы уже форкнули %s fork_to_different_account=Ответвление для другой учётной записи fork_visibility_helper=Видимость форкнутого репозитория изменить нельзя. +fork_branch=Ветка для клонирования в форк all_branches=Все ветки use_template=Использовать этот шаблон clone_in_vsc=Клонировать в VS Code @@ -1316,7 +1317,7 @@ projects.card_type.desc=Предпросмотр карточек projects.card_type.images_and_text=Изображения и текст projects.card_type.text_only=Только текст -issues.desc=Организация отчетов об ошибках, задач и этапов. +issues.desc=Организация отчетов об ошибках, заданий и этапов. issues.filter_assignees=Фильтр назначений issues.filter_milestones=Фильтр этапов issues.filter_projects=Фильтровать проекты @@ -1801,7 +1802,13 @@ milestones.filter_sort.most_issues=Большинство задач milestones.filter_sort.least_issues=Меньшинство задач signing.will_sign=Этот коммит будет подписан ключом «%s». +signing.wont_sign.never=Коммиты никогда не подписываются. +signing.wont_sign.always=Коммиты всегда подписываются. +signing.wont_sign.pubkey=Этот коммит не будет подписан, поскольку к вашей учётной записи не привязано публичного ключа. +signing.wont_sign.twofa=Для подписания коммитов у вас должна быть включена двухфакторная аутентификация. signing.wont_sign.basesigned=Слияние не будет подписано, так как базовый коммит не подписан. +signing.wont_sign.commitssigned=Слияние не будет подписано, так как все связанные коммиты не подписаны. +signing.wont_sign.approved=Слияние не будет подписано, так как запрос на слияние не одобрен. signing.wont_sign.not_signed_in=Вы не вошли в систему. ext_wiki=Доступ к внешней вики @@ -1849,8 +1856,8 @@ activity.merged_prs_count_1=Принятый запрос на слияние activity.merged_prs_count_n=Принятых запросов на слияние activity.opened_prs_count_1=Новый запрос на слияние activity.opened_prs_count_n=Новых запросов на слияние -activity.title.user_1=%d пользователь -activity.title.user_n=%d пользователей +activity.title.user_1=%d пользователем +activity.title.user_n=%d пользователями activity.title.prs_1=%d запрос на слияние activity.title.prs_n=%d запросов на слияние activity.title.prs_merged_by=%s приняты %s @@ -1861,9 +1868,9 @@ activity.active_issues_count_1=%d Активная задача activity.active_issues_count_n=%d Активных задач activity.closed_issues_count_1=Закрытая задача activity.closed_issues_count_n=Закрытых задач -activity.title.issues_1=%d Задача -activity.title.issues_n=%d Задач -activity.title.issues_closed_from=%s закрыто %s +activity.title.issues_1=%d задача +activity.title.issues_n=%d задач +activity.title.issues_closed_from=%s закрыто от %s activity.title.issues_created_by=%s создано %s activity.closed_issue_label=Закрыто activity.new_issues_count_1=Новая задача @@ -1881,8 +1888,8 @@ activity.no_git_activity=В этот период не было новых ко activity.git_stats_exclude_merges=За исключением слияний, activity.git_stats_author_1=%d автор activity.git_stats_author_n=%d автора(ов) -activity.git_stats_pushed_1=отправлен -activity.git_stats_pushed_n=отправлено +activity.git_stats_pushed_1=отправил +activity.git_stats_pushed_n=отправили activity.git_stats_commit_1=%d коммит activity.git_stats_commit_n=%d коммитов activity.git_stats_push_to_branch=в %s и @@ -1890,8 +1897,8 @@ activity.git_stats_push_to_all_branches=во все ветки. activity.git_stats_on_default_branch=На %s, activity.git_stats_file_1=%d файл activity.git_stats_file_n=%d файлов -activity.git_stats_files_changed_1=изменилось -activity.git_stats_files_changed_n=изменено +activity.git_stats_files_changed_1=изменён, +activity.git_stats_files_changed_n=изменены, activity.git_stats_additions=и там было activity.git_stats_addition_1=%d добавление activity.git_stats_addition_n=%d добавлений @@ -1942,6 +1949,7 @@ settings.mirror_settings.last_update=Последнее обновление settings.mirror_settings.push_mirror.none=Push-зеркало не добавлено settings.mirror_settings.push_mirror.remote_url=URL удалённого хранилища settings.mirror_settings.push_mirror.add=Добавить Push-зеркало +settings.mirror_settings.push_mirror.edit_sync_time=Изменить интервал синхронизации зеркала settings.sync_mirror=Синхронизировать settings.site=Сайт @@ -2146,6 +2154,7 @@ settings.event_pull_request_sync_desc=Запрос на слияние синх settings.event_pull_request_review_request=Запрошена рецензия для запроса на слияние settings.event_pull_request_review_request_desc=Создан или удалён запрос на рецензию для запроса на слияние. settings.event_pull_request_approvals=Утверждения запросов на слияние +settings.event_pull_request_merge=Удовлетворение запросов на слияние settings.event_package=Пакеты settings.event_package_desc=Пакет создан или удален в репозитории. settings.branch_filter=Фильтр веток @@ -2208,6 +2217,7 @@ settings.protect_disable_push=Отключить отправку settings.protect_disable_push_desc=Отправка не будет разрешена в эту ветку. settings.protect_enable_push=Включить отправку settings.protect_enable_push_desc=Любому, у кого есть доступ на запись, будет разрешена отправка изменений в эту ветку (но не принудительная отправка). +settings.protect_enable_merge=Разрешить всем settings.protect_enable_merge_desc=Все, у кого есть доступ на запись, смогут удовлетворять запросы на слияние в эту ветку. settings.protect_whitelist_committers=Ограничение отправки по белому списку settings.protect_whitelist_committers_desc=Только пользователям или командам из белого списка будет разрешена отправка изменений в эту ветку (но не принудительная отправка). @@ -2432,6 +2442,7 @@ branch.already_exists=Ветка с именем «%s» уже существу branch.delete_head=Удалить branch.delete=Удалить ветку «%s» branch.delete_html=Удалить ветку +branch.delete_desc=Удаление ветки необратимо. Несмотря на то, что удаленная ветка может просуществовать некоторое время перед тем, как она будет окончательно удалена, это действие НЕВОЗМОЖНО отменить в большинстве случаев. Продолжить? branch.deletion_success=Ветка «%s» удалена. branch.deletion_failed=Не удалось удалить ветку «%s». branch.delete_branch_has_new_commits=Ветку «%s» нельзя удалить, поскольку после слияния были добавлены новые коммиты. @@ -2470,7 +2481,7 @@ tag.create_success=Тег «%s» создан. topic.manage_topics=Редактировать тематические метки topic.done=Сохранить -topic.count_prompt=Вы не можете выбрать более 25 тем +topic.count_prompt=Нельзя выбрать более 25 тем find_file.go_to_file=Перейти к файлу find_file.no_matching=Совпадающих файлов не найдено @@ -2509,6 +2520,7 @@ form.create_org_not_allowed=Этому пользователю не разре settings=Настройки settings.options=Организация settings.full_name=Полное имя +settings.email=Почта для связи settings.website=Сайт settings.location=Местоположение settings.permission=Разрешения @@ -2522,6 +2534,7 @@ settings.visibility.private_shortname=Приватный settings.update_settings=Обновить настройки settings.update_setting_success=Настройки организации обновлены. +settings.change_orgname_prompt=Обратите внимание: изменение названия организации также изменит URL вашей организации и освободит старое имя. settings.change_orgname_redirect_prompt=Старое имя будет перенаправлено до тех пор, пока оно не будет введено. settings.update_avatar_success=Аватар организации обновлён. settings.delete=Удалить организацию @@ -2625,17 +2638,18 @@ dashboard.operation_run=Запуск dashboard.clean_unbind_oauth=Очистить список незавершённых авторизаций OAuth dashboard.clean_unbind_oauth_success=Все незавершённые связи OAuth были удалены. dashboard.task.started=Началось задание: %[1]s -dashboard.task.process=Задача: %[1]s -dashboard.task.cancelled=Задача: %[1]s отменена: %[3]s -dashboard.task.error=Ошибка в Задаче: %[1]s: %[3]s -dashboard.task.finished=Задача: %[1]s, начатая %[2]s завершена -dashboard.task.unknown=Неизвестная задача: %[1]s -dashboard.cron.started=Стартовал Cron: %[1]s -dashboard.cron.process=Cron: %[1]s -dashboard.cron.error=Ошибка в задаче Cron: %s: %[3]s -dashboard.cron.finished=Крон: %[1]s завершено +dashboard.task.process=Задание: %[1]s +dashboard.task.cancelled=Задание %[1]s отменено: %[3]s +dashboard.task.error=Ошибка в задании: %[1]s: %[3]s +dashboard.task.finished=Задание %[1]s, начатое %[2]s, завершено +dashboard.task.unknown=Неизвестное задание: %[1]s +dashboard.cron.started=Планировщик запущен: %[1]s +dashboard.cron.process=Планировщик: %[1]s +dashboard.cron.cancelled=Планировщик: %[1]s отменено: %[3]s +dashboard.cron.error=Ошибка в запланированном задании: %s: %[3]s +dashboard.cron.finished=Планировщик: %[1]s завершено dashboard.delete_inactive_accounts=Удалить все неактивированные учётные записи -dashboard.delete_inactive_accounts.started=Удалить все запущенные задачи неактивированных аккаунтов. +dashboard.delete_inactive_accounts.started=Удаление всех неактивированных учётных записей началось. dashboard.delete_repo_archives=Удалить все архивы репозиториев (ZIP, TAR.GZ, и т.д..) dashboard.delete_repo_archives.started=Удаление всех архивов репозитория началось. dashboard.delete_missing_repos=Удалить все записи о репозиториях с отсутствующими файлами Git @@ -2689,8 +2703,8 @@ dashboard.delete_old_actions.started=Удалите все старые дейс dashboard.update_checker=Проверка обновлений dashboard.delete_old_system_notices=Удалить все старые системные уведомления из базы данных dashboard.gc_lfs=Выполнить сборку мусора метаобъектов LFS -dashboard.stop_zombie_tasks=Остановить задачи-зомби -dashboard.stop_endless_tasks=Остановить бесконечные задачи +dashboard.stop_zombie_tasks=Остановить задания-зомби +dashboard.stop_endless_tasks=Остановить бесконечные задания dashboard.cancel_abandoned_jobs=Отменить брошенные задания users.user_manage_panel=Панель управления пользователями @@ -2700,6 +2714,8 @@ users.full_name=Полное имя users.activated=Активирован users.admin=Администратор users.restricted=Ограничено +users.reserved=Зарезервировано +users.bot=Бот users.2fa=Двухфакторная авторизация users.repos=Репозитории users.created=Создано @@ -2746,6 +2762,7 @@ users.list_status_filter.is_prohibit_login=Запретить вход users.list_status_filter.not_prohibit_login=Разрешить вход users.list_status_filter.is_2fa_enabled=2FA включено users.list_status_filter.not_2fa_enabled=2FA отключено +users.details=О пользователе emails.email_manage_panel=Управление эл. почтой пользователя emails.primary=Первичный @@ -2782,6 +2799,7 @@ repos.lfs_size=Размер LFS packages.package_manage_panel=Управление пакетами packages.total_size=Общий размер: %s packages.unreferenced_size=Размер по ссылке: %s +packages.cleanup=Очистить устаревшие данные packages.owner=Владелец packages.creator=Автор packages.name=Наименование @@ -2928,6 +2946,7 @@ config.disable_router_log=Отключение журнала маршрутиз config.run_user=Запуск от имени пользователя config.run_mode=Режим выполнения config.git_version=Версия Git +config.app_data_path=Путь к данным приложения config.repo_root_path=Путь до папки репозиториев config.lfs_root_path=Корневой путь LFS config.log_file_root_path=Путь к журналу @@ -3053,7 +3072,7 @@ config.set_setting_failed=Задать параметр %s не удалось monitor.stats=Статистика -monitor.cron=Задачи cron +monitor.cron=Запланированные задания monitor.name=Название monitor.schedule=Расписание monitor.next=Следующий раз @@ -3100,7 +3119,7 @@ notices.delete_selected=Удалить выбранные notices.delete_all=Удалить все уведомления notices.type=Тип notices.type_1=Репозиторий -notices.type_2=Задача +notices.type_2=Задание notices.desc=Описание notices.op=Oп. notices.delete_success=Уведомления системы были удалены. @@ -3200,6 +3219,7 @@ desc=Управление пакетами репозитория. empty=Пока нет пакетов. empty.documentation=Дополнительную информацию о реестре пакетов можно найти в документации. empty.repo=Вы загрузили пакет, но он здесь не отображается? Перейдите в настройки пакета и свяжите его с этим репозиторием. +registry.documentation=Для получения дополнительной информации о реестре %s смотрите документацию. filter.type=Тип filter.type.all=Все filter.no_result=Фильтр не дал результатов. @@ -3289,6 +3309,8 @@ pub.install=Чтобы установить пакет с помощью Dart, pypi.requires=Требуется Python pypi.install=Чтобы установить пакет с помощью pip, выполните следующую команду: rpm.registry=Настроить реестр из командной строки: +rpm.distros.redhat=на дистрибутивах семейства RedHat +rpm.distros.suse=на дистрибутивах семейства SUSE rpm.install=Чтобы установить пакет, выполните следующую команду: rubygems.install=Чтобы установить пакет с помощью gem, выполните следующую команду: rubygems.install2=или добавьте его в Gemfile: @@ -3313,6 +3335,7 @@ settings.delete.success=Пакет удалён. settings.delete.error=Не удалось удалить пакет. owner.settings.cargo.title=Индекс реестра Cargo owner.settings.cargo.initialize=Инициализировать индекс +owner.settings.cargo.initialize.description=Для использования реестра Cargo необходим специальный Git-репозиторий с индексом. Эта опция (пере)создаст репозиторий и настроит его автоматически. owner.settings.cargo.initialize.error=Не удалось инициализировать индекс Cargo: %v owner.settings.cargo.initialize.success=Индекс Cargo успешно создан. owner.settings.cargo.rebuild=Перестроить индекс @@ -3381,7 +3404,8 @@ runners.description=Описание runners.labels=Метки runners.last_online=Был онлайн runners.runner_title=Раннер -runners.task_list=Недавние задачи на раннере +runners.task_list=Недавние задания на раннере +runners.task_list.no_tasks=Задания пока нет. runners.task_list.run=Запуск runners.task_list.status=Статус runners.task_list.repository=Репозиторий @@ -3395,7 +3419,7 @@ runners.delete_runner=Удалить этот раннер runners.delete_runner_success=Раннер успешно удалён runners.delete_runner_failed=Не удалось удалить раннер runners.delete_runner_header=Подтвердите удаление раннера -runners.delete_runner_notice=Если на этом раннере выполняется задача, она будет завершена и помечена как неудачная. Это может нарушить рабочий поток сборки. +runners.delete_runner_notice=Если на этом раннере выполняется задание, оно будет завершено и помечено как неудачное. Это может нарушить рабочий поток сборки. runners.none=Нет доступных раннеров runners.status.unspecified=Неизвестно runners.status.idle=Простаивает @@ -3406,10 +3430,19 @@ runners.reset_registration_token_success=Токен регистрации ра runs.all_workflows=Все рабочие потоки runs.commit=коммит +runs.pushed_by=отправлено runs.invalid_workflow_helper=Файл конфигурации рабочего потока некорректен. Пожалуйста, проверьте конфигурационный файл: %s runs.no_matching_runner_helper=Нет подходящего раннера: %s +runs.actor=Актор runs.status=Статус +runs.actors_no_select=Все акторы +runs.no_runs=Рабочий поток ещё не запускался. +workflow.disable=Выключить рабочий поток +workflow.disable_success=Рабочий поток «%s» успешно выключен. +workflow.enable=Включить рабочий поток +workflow.enable_success=Рабочий поток «%s» успешно включен. +workflow.disabled=Рабочий поток выключен. need_approval_desc=Требуется одобрение, чтобы запустить рабочие потоки для запроса на слияние. From 5380fd5d6d9fc1f1b280bf39a3906555985987ee Mon Sep 17 00:00:00 2001 From: Anudeep Reddy Date: Tue, 14 Nov 2023 06:45:45 +0530 Subject: [PATCH 004/753] fixed duplicate attachments on dump on windows (#28019) Hi, This PR fixes #27988. The use of `path.join`(which uses `/` as the file separator) to construct paths and comparing them with paths constructed using `filepath.join`(which uses platform specific file separator) is the root cause of this issue. The desired behavior is to ignore attachments when dumping data directory. Due to the what's mentioned above, the function `addRecursiveExclude` is not actually ignoring the attachments directory and is being written to the archive. The attachment directory is again added to the archive (with different file separator as mentioned in the issue) causing a duplicate entry on windows. The solution is to use `filepath.join` in `addResursiveExclude` to construct `currentAbsPath`. --- cmd/dump.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/dump.go b/cmd/dump.go index 97f292ae09..69ecdcec12 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -452,7 +452,7 @@ func addRecursiveExclude(w archiver.Writer, insidePath, absPath string, excludeA return err } for _, file := range files { - currentAbsPath := path.Join(absPath, file.Name()) + currentAbsPath := filepath.Join(absPath, file.Name()) currentInsidePath := path.Join(insidePath, file.Name()) if file.IsDir() { if !util.SliceContainsString(excludeAbsPath, currentAbsPath) { From 83c30634a40f21a7b2d5c7b474e78e02d1276ff4 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Tue, 14 Nov 2023 13:58:01 +0900 Subject: [PATCH 005/753] Add word break to the repo list in admin settings page (#28034) Before: ![image](https://github.com/go-gitea/gitea/assets/18380374/ed464937-e20d-4f5b-b997-e86c2d96469d) After: ![image](https://github.com/go-gitea/gitea/assets/18380374/471e77b3-516e-4ae9-b901-0cf8745eb9aa) --- templates/admin/repo/list.tmpl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/admin/repo/list.tmpl b/templates/admin/repo/list.tmpl index 2581864547..7102f73305 100644 --- a/templates/admin/repo/list.tmpl +++ b/templates/admin/repo/list.tmpl @@ -47,13 +47,13 @@ {{.ID}} - {{.Owner.Name}} + {{.Owner.Name}} {{if .Owner.Visibility.IsPrivate}} {{svg "octicon-lock"}} {{end}} - {{.Name}} + {{.Name}} {{if .IsArchived}} {{ctx.Locale.Tr "repo.desc.archived"}} {{end}} From 48b9d9859331cb7a76ad5719ebbb21e2f598b75b Mon Sep 17 00:00:00 2001 From: JakobDev Date: Tue, 14 Nov 2023 12:42:23 +0100 Subject: [PATCH 006/753] Fix viewing wiki commit on empty repo (#28040) Fixes https://codeberg.org/forgejo/forgejo/issues/1758 For some weird reason we need to cast this nil. --- routers/web/repo/middlewares.go | 1 - 1 file changed, 1 deletion(-) diff --git a/routers/web/repo/middlewares.go b/routers/web/repo/middlewares.go index b50e96be3c..5f4a219aa3 100644 --- a/routers/web/repo/middlewares.go +++ b/routers/web/repo/middlewares.go @@ -16,7 +16,6 @@ import ( // SetEditorconfigIfExists set editor config as render variable func SetEditorconfigIfExists(ctx *context.Context) { if ctx.Repo.Repository.IsEmpty { - ctx.Data["Editorconfig"] = nil return } From 58b27799863f97af18097dde241af28e1361ef75 Mon Sep 17 00:00:00 2001 From: Denys Konovalov Date: Tue, 14 Nov 2023 14:55:16 +0100 Subject: [PATCH 007/753] Add v1.21.0 changelog (#28005) Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: silverwind --- CHANGELOG.md | 449 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 448 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea0f80c0c9..8f81244644 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,454 @@ This changelog goes through all the changes that have been made in each release without substantial changes to our git log; to see the highlights of what has been added to each release, please refer to the [blog](https://blog.gitea.com). +## [1.21.0](https://github.com/go-gitea/gitea/releases/tag/1.21.0) - 2023-11-14 + +* BREAKING + * Restrict certificate type for builtin SSH server (#26789) + * Refactor to use urfave/cli/v2 (#25959) + * Move public asset files to the proper directory (#25907) + * Remove commit status running and warning to align GitHub (#25839) (partially reverted: Restore warning commit status (#27504) (#27529)) + * Remove "CHARSET" config option for MySQL, always use "utf8mb4" (#25413) + * Set SSH_AUTHORIZED_KEYS_BACKUP to false (#25412) +* FEATURES + * User details page (#26713) + * Chore(actions): support cron schedule task (#26655) + * Support rebuilding issue indexer manually (#26546) + * Allow to archive labels (#26478) + * Add disable workflow feature (#26413) + * Support `.git-blame-ignore-revs` file (#26395) + * Pre-register OAuth2 applications for git credential helpers (#26291) + * Add `Retry` button when creating a mirror-repo fails (#26228) + * Artifacts retention and auto clean up (#26131) + * Serve pre-defined files in "public", add "security.txt", add CORS header for ".well-known" (#25974) + * Implement auto-cancellation of concurrent jobs if the event is push (#25716) + * Newly pushed branches hints on repository home page (#25715) + * Display branch commit status (#25608) + * Add direct serving of package content (#25543) + * Add commits dropdown in PR files view and allow commit by commit review (#25528) + * Allow package cleanup from admin page (#25307) + * Batch delete issue and improve tippy opts (#25253) + * Show branches and tags that contain a commit (#25180) + * Add actor and status dropdowns to run list (#25118) + * Allow Organisations to have a E-Mail (#25082) + * Add codeowners feature (#24910) + * Actions Artifacts support uploading multiple files and directories (#24874) + * Support configuration variables on Gitea Actions (#24724) + * Support downloading raw task logs (#24451) +* API + * Unify two factor check (#27915) (#27929) + * Fix package webhook (#27839) (#27855) + * Fix/upload artifact error windows (#27802) (#27840) + * Fix bad method call when deleting user secrets via API (#27829) (#27831) + * Do not force creation of _cargo-index repo on publish (#27266) (#27765) + * Delete repos of org when purge delete user (#27273) (#27728) + * Fix org team endpoint (#27721) (#27727) + * Api: GetPullRequestCommits: return file list (#27483) (#27539) + * Don't let API add 2 exclusive labels from same scope (#27433) (#27460) + * Redefine the meaning of column is_active to make Actions Registration Token generation easier (#27143) (#27304) + * Fix PushEvent NullPointerException jenkinsci/github-plugin (#27203) (#27251) + * Fix organization field being null in POST /orgs/{orgid}/teams (#27150) (#27163) + * Allow empty Conan files (#27092) + * Fix token endpoints ignore specified account (#27080) + * Reduce usage of `db.DefaultContext` (#27073) (#27083) (#27089) (#27103) (#27262) (#27265) (#27347) (#26076) + * Make SSPI auth mockable (#27036) + * Extract auth middleware from service (#27028) + * Add `RemoteAddress` to mirrors (#26952) + * Feat(API): add routes and functions for managing user's secrets (#26909) + * Feat(API): add secret deletion functionality for repository (#26808) + * Feat(API): add route and implementation for creating/updating repository secret (#26766) + * Add Upload URL to release API (#26663) + * Feat(API): update and delete secret for managing organization secrets (#26660) + * Feat: implement organization secret creation API (#26566) + * Add API route to list org secrets (#26485) + * Set commit id when ref used explicitly (#26447) + * PATCH branch-protection updates check list even when checks are disabled (#26351) + * Add file status for API "Get a single commit from a repository" (#16205) (#25831) + * Add API for changing Avatars (#25369) +* BUGFIXES + * Fix viewing wiki commit on empty repo (#28040) (#28044) + * Enable system users for comment.LoadPoster (#28014) (#28032) + * Fixed duplicate attachments on dump on windows (#28019) (#28031) + * Fix wrong xorm Delete usage(backport for 1.21) (#28002) + * Add word-break to repo description in home page (#27924) (#27957) + * Fix rendering assignee changed comments without assignee (#27927) (#27952) + * Add word break to release title (#27942) (#27947) + * Fix JS NPE when viewing specific range of PR commits (#27912) (#27923) + * Show correct commit sha when viewing single commit diff (#27916) (#27921) + * Fix 500 when deleting a dismissed review (#27903) (#27910) + * Fix DownloadFunc when migrating releases (#27887) (#27890) + * Fix http protocol auth (#27875) (#27876) + * Refactor postgres connection string building (#27723) (#27869) + * Close all hashed buffers (#27787) (#27790) + * Fix label render containing invalid HTML (#27752) (#27762) + * Fix duplicate project board when hitting `enter` key (#27746) (#27751) + * Fix `link-action` redirect network error (#27734) (#27749) + * Fix sticky diff header background (#27697) (#27712) + * Always delete existing scheduled action tasks (#27662) (#27688) + * Support allowed hosts for webhook to work with proxy (#27655) (#27675) + * Fix poster is not loaded in get default merge message (#27657) (#27666) + * Improve dropdown button alignment and fix hover bug (#27632) (#27637) + * Improve retrying index issues (#27554) (#27634) + * Fix 404 when deleting Docker package with an internal version (#27615) (#27630) + * Backport manually for a tmpl issue in v1.21 (#27612) + * Don't show Link to TOTP if not set up (#27585) (#27588) + * Fix data-race bug when accessing task.LastRun (#27584) (#27586) + * Fix attachment download bug (#27486) (#27571) + * Respect SSH.KeygenPath option when calculating ssh key fingerprints (#27536) (#27551) + * Improve dropdown's behavior when there is a search input in menu (#27526) (#27534) + * Fix panic in storageHandler (#27446) (#27479) + * When comparing with an non-exist repository, return 404 but 500 (#27437) (#27442) + * Fix pr template (#27436) (#27440) + * Fix git 2.11 error when checking IsEmpty (#27393) (#27397) + * Allow get release download files and lfs files with oauth2 token format (#26430) (#27379) + * Fix missing ctx for GetRepoLink in dashboard (#27372) (#27375) + * Absolute positioned checkboxes overlay floated elements (#26870) (#27366) + * Introduce fixes and more rigorous tests for 'Show on a map' feature (#26803) (#27365) + * Fix repo count in org action settings (#27245) (#27353) + * Add logs for data broken of comment review (#27326) (#27345) + * Fix the approval count of PR when there is no protection branch rule (#27272) (#27343) + * Fix Bug in Issue Config when only contact links are set (#26521) (#27334) + * Improve issue history dialog and make poster can delete their own history (#27323) (#27327) + * Fix orphan check for deleted branch (#27310) (#27321) + * Fix protected branch icon location (#26576) (#27317) + * Fix yaml test (#27297) (#27303) + * Fix some animation bugs (#27287) (#27294) + * Fix incorrect change from #27231 (#27275) (#27282) + * Add missing public user visibility in user details page (#27246) (#27250) + * Fix EOL handling in web editor (#27141) (#27234) + * Fix issues on action runners page (#27226) (#27233) + * Quote table `release` in sql queries (#27205) (#27218) + * Fix release URL in webhooks (#27182) (#27185) + * Fix review request number and add more tests (#27104) (#27168) + * Fix the variable regexp pattern on web page (#27161) (#27164) + * Fix: treat tab "overview" as "repositories" in user profiles without readme (#27124) + * Fix NPE when editing OAuth2 applications (#27078) + * Fix the incorrect route path in the user edit page. (#27007) + * Fix the secret regexp pattern on web page (#26910) + * Allow users with write permissions for issues to add attachments with API (#26837) + * Make "link-action" backend code respond correct JSON content (#26680) + * Use line-height: normal by default (#26635) + * Fix NPM packages name validation (#26595) + * Rewrite the DiffFileTreeItem and fix misalignment (#26565) + * Return empty when searching issues with no repos (#26545) + * Explain SearchOptions and fix ToSearchOptions (#26542) + * Add missing triggers to update issue indexer (#26539) + * Handle base64 decoding correctly to avoid panic (#26483) + * Avoiding accessing undefined mentionValues (#26461) + * Fix incorrect redirection in new issue using references (#26440) + * Fix the bug when getting files changed for `pull_request_target` event (#26320) + * Remove IsWarning in tmpl (#26120) + * Fix loading `LFS_JWT_SECRET` from wrong section (#26109) + * Fixing redirection issue for logged-in users (#26105) + * Improve "gitea doctor" sub-command and fix "help" commands (#26072) + * Fix the truncate and alignment problem for some admin tables (#26042) + * Update minimum password length requirements (#25946) + * Do not "guess" the file encoding/BOM when using API to upload files (#25828) + * Restructure issue list template, styles (#25750) + * Fix `ref` for workflows triggered by `pull_request_target` (#25743) + * Fix issues indexer document mapping (#25619) + * Use JSON response for "user/logout" (#25522) + * Fix migrate page layout on mobile (#25507) + * Link to existing PR when trying to open a new PR on the same branches (#25494) + * Do not publish docker release images on `-dev` tags (#25471) + * Support `pull_request_target` event (#25229) + * Modify the content format of the Feishu webhook (#25106) +* ENHANCEMENTS + * Render email addresses as such if followed by punctuation (#27987) (#27992) + * Show error toast when file size exceeds the limits (#27985) (#27986) + * Fix citation error when the file size is larger than 1024 bytes (#27958) (#27965) + * Remove action runners on user deletion (#27902) (#27908) + * Remove set tabindex on view issue (#27892) (#27896) + * Reduce margin/padding on flex-list items and divider (#27872) (#27874) + * Change katex limits (#27823) (#27868) + * Clean up template locale usage (#27856) (#27857) + * Add dedicated class for empty placeholders (#27788) (#27792) + * Add gap between diff boxes (#27776) (#27781) + * Fix incorrect "tab" parameter for repo search sub-template (#27755) (#27764) + * Enable followCursor for language stats bar (#27713) (#27739) + * Improve diff tree spacing (#27714) (#27719) + * Feed UI Improvements (#27356) (#27717) + * Improve feed icons and feed merge text color (#27498) (#27716) + * [FIX] resolve confusing colors in languages stats by insert a gap (#27704) (#27715) + * Add doctor dbconsistency fix to delete repos with no owner (#27290) (#27693) + * Fix required checkboxes in issue forms (#27592) (#27692) + * Hide archived labels by default from the suggestions when assigning labels for an issue (#27451) (#27661) + * Cleanup repo details icons/labels (#27644) (#27654) + * Keep filter when showing unfiltered results on explore page (#27192) (#27589) + * Show manual cron run's last time (#27544) (#27577) + * Revert "Fix pr template (#27436)" (#27567) + * Increase queue length (#27555) (#27562) + * Avoid run change title process when the title is same (#27467) (#27558) + * Remove max-width and add hide text overflow (#27359) (#27550) + * Add hover background to wiki list page (#27507) (#27521) + * Fix mermaid flowchart margin issue (#27503) (#27516) + * Refactor system setting (#27000) (#27452) + * Fix missing `ctx` in new_form.tmpl (#27434) (#27438) + * Add Index to `action.user_id` (#27403) (#27425) + * Don't use subselect in `DeleteIssuesByRepoID` (#27332) (#27408) + * Add support for HEAD ref in /src/branch and /src/commit routes (#27384) (#27407) + * Make Actions tasks/jobs timeouts configurable by the user (#27400) (#27402) + * Hide archived labels when filtering by labels on the issue list (#27115) (#27381) + * Highlight user details link (#26998) (#27376) + * Add protected branch name description (#27257) (#27351) + * Improve tree not found page (#26570) (#27346) + * Add Index to `comment.dependent_issue_id` (#27325) (#27340) + * Improve branch list UI (#27319) (#27324) + * Fix divider in subscription page (#27298) (#27301) + * Add missed return to actions view fetch (#27289) (#27293) + * Backport ctx locale refactoring manually (#27231) (#27259) (#27260) + * Disable `Test Delivery` and `Replay` webhook buttons when webhook is inactive (#27211) (#27253) + * Use mask-based fade-out effect for `.new-menu` (#27181) (#27243) + * Cleanup locale function usage (#27227) (#27240) + * Fix z-index on markdown completion (#27237) (#27239) + * Fix Fomantic UI dropdown icon bug when there is a search input in menu (#27225) (#27228) + * Allow copying issue comment link on archived repos and when not logged in (#27193) (#27210) + * Fix: text decorator on issue sidebar menu label (#27206) (#27209) + * Fix dropdown icon position (#27175) (#27177) + * Add index to `issue_user.issue_id` (#27154) (#27158) + * Increase auth provider icon size on login page (#27122) + * Remove a `gt-float-right` and some unnecessary helpers (#27110) + * Change green buttons to primary color (#27099) + * Use db.WithTx for AddTeamMember to avoid ctx abuse (#27095) + * Use `print` instead of `printf` (#27093) + * Remove the useless function `GetUserIssueStats` and move relevant tests to `indexer_test.go` (#27067) + * Search branches (#27055) + * Display all user types and org types on admin management UI (#27050) + * Ui correction in mobile view nav bar left aligned items. (#27046) + * Chroma color tweaks (#26978) + * Move some functions to service layer (#26969) + * Improve "language stats" UI (#26968) + * Replace `util.SliceXxx` with `slices.Xxx` (#26958) + * Refactor dashboard/feed.tmpl (#26956) + * Move repository deletion to service layer (#26948) + * Fix the missing repo count (#26942) + * Improve hint when uploading a too large avatar (#26935) + * Extract common code to new template (#26933) + * Move createrepository from module to service layer (#26927) + * Move notification interface to services layer (#26915) + * Move feed notification service layer (#26908) + * Move ui notification to service layer (#26907) + * Move indexer notification to service layer (#26906) + * Move mail notification logic to service layer (#26905) + * Extract common code to new template (#26903) + * Show queue's active worker number (#26896) + * Fix media description render for orgmode (#26895) + * Remove CSS `has` selector and improve various styles (#26891) + * Relocate the `RSS user feed` button (#26882) + * Refactor "shortsha" (#26877) + * Refactor `og:description` to limit the max length (#26876) + * Move web/api context related testing function into a separate package (#26859) + * Redable error on S3 storage connection failure (#26856) + * Improve opengraph previews (#26851) + * Add more descriptive error on forgot password page (#26848) + * Show always repo count in header (#26842) + * Remove "TODO" tasks from CSS file (#26835) + * Render code blocks in repo description (#26830) + * Minor dashboard tweaks, fix flex-list margins (#26829) + * Remove polluted `.ui.right` (#26825) + * Display archived labels specially when listing labels (#26820) + * Remove polluted ".ui.left" style (#26809) + * Make it posible to customize nav text color via css var (#26807) + * Refactor lfs requests (#26783) + * Improve flex list item padding (#26779) + * Remove fomantic `text` module (#26777) + * Remove fomantic `item` module (#26775) + * Remove redundant nil check in `WalkGitLog` (#26773) + * Reduce some allocations in type conversion (#26772) + * Refactor some CSS styles and simplify code (#26771) + * Unify `border-radius` behavior (#26770) + * Improve modal dialog UI (#26764) + * Allow "latest" to be used in release vTag when downloading file (#26748) + * Adding hint `Archived` to archive label. (#26741) + * Move `modules/mirror` to `services` (#26737) + * Add "dir=auto" for input/textarea elements by default (#26735) + * Add auth-required to config.json for Cargo http registry (#26729) + * Simplify helper CSS classes and avoid abuse (#26728) + * Make web context initialize correctly for different cases (#26726) + * Focus editor on "Write" tab click (#26714) + * Remove incorrect CSS helper classes (#26712) + * Fix review bar misalignment (#26711) + * Add reverseproxy auth for API back with default disabled (#26703) + * Add default label in branch select list (#26697) + * Improve Image Diff UI (#26696) + * Fixed text overflow in dropdown menu (#26694) + * [Refactor] getIssueStatsChunk to move inner function into own one (#26671) + * Remove fomantic loader module (#26670) + * Add `member`, `collaborator`, `contributor`, and `first-time contributor` roles and tooltips (#26658) + * Improve some flex layouts (#26649) + * Improve the branch selector tab UI (#26631) + * Improve show role (#26621) + * Remove avatarHTML from template helpers (#26598) + * Allow text selection in actions step header (#26588) + * Improve translation of milestone filters (#26569) + * Add optimistic lock to ActionRun table (#26563) + * Update team invitation email link (#26550) + * Differentiate better between user settings and admin settings (#26538) + * Check disabled workflow when rerun jobs (#26535) + * Improve deadline icon location in milestone list page (#26532) + * Improve repo sub menu (#26531) + * Fix the display of org level badges (#26504) + * Rename `Sync2` -> `Sync` (#26479) + * Fix stderr usages (#26477) + * Remove fomantic transition module (#26469) + * Refactor tests (#26464) + * Refactor project templates (#26448) + * Fall back to esbuild for css minify (#26445) + * Always show usernames in reaction tooltips (#26444) + * Use correct pull request commit link instead of a generic commit link (#26434) + * Refactor "editorconfig" (#26391) + * Make `user-content-* ` consistent with github (#26388) + * Remove unnecessary template helper repoAvatar (#26387) + * Remove unnecessary template helper DisableGravatar (#26386) + * Use template context function for avatar rendering (#26385) + * Rename code_langauge.go to code_language.go (#26377) + * Use more `IssueList` instead of `[]*Issue` (#26369) + * Do not highlight `#number` in documents (#26365) + * Fix display problems of members and teams unit (#26363) + * Fix 404 error when remove self from an organization (#26362) + * Improve CLI and messages (#26341) + * Refactor backend SVG package and add tests (#26335) + * Add link to job details and tooltip to commit status in repo list in dashboard (#26326) + * Use yellow if an approved review is stale (#26312) + * Remove commit load branches and tags in wiki repo (#26304) + * Add highlight to selected repos in milestone dashboard (#26300) + * Delete `issue_service.CreateComment` (#26298) + * Do not show Profile README when repository is private (#26295) + * Tweak actions menu (#26278) + * Start using template context function (#26254) + * Use calendar icon for `Joined on...` in profiles (#26215) + * Add 'Show on a map' button to Location in profile, fix layout (#26214) + * Render plaintext task list items for markdown files (#26186) + * Add tooltip to describe LFS table column and color `delete LFS file` button red (#26181) + * Release attachments duplicated check (#26176) + * De-emphasize issue sidebar buttons (#26171) + * Fixing the align of commit stats in commit_page template. (#26161) + * Allow editing push mirrors after creation (#26151) + * Move web JSON functions to web context and simplify code (#26132) + * Refactor improve NoBetterThan (#26126) + * Improve clickable area in repo action view page (#26115) + * Add context parameter to some database functions (#26055) + * Docusaurus-ify (#26051) + * Improve text for empty issue/pr description (#26047) + * Categorize admin settings sidebar panel (#26030) + * Remove redundant "RouteMethods" method (#26024) + * Refactor and enhance issue indexer to support both searching, filtering and paging (#26012) + * Add a link to OpenID Issuer URL in WebFinger response (#26000) + * Fix UI for release tag page / wiki page / subscription page (#25948) + * Support copy protected branch from template repository (#25889) + * Improve display of Labels/Projects/Assignees sort options (#25886) + * Fix margin on the new/edit project page. (#25885) + * Show image size on view page (#25884) + * Remove ref name in PR commits page (#25876) + * Allow the use of alternative net.Listener implementations by downstreams (#25855) + * Refactor "Content" for file uploading (#25851) + * Add error info if no user can fork the repo (#25820) + * Show edit title button on commits tab of PR, too (#25791) + * Introduce `flex-list` & `flex-item` elements for Gitea UI (#25790) + * Don't stack PR tab menu on small screens (#25789) + * Repository Archived text title center align (#25767) + * Make route middleware/handler mockable (#25766) + * Move issue filters to shared template (#25729) + * Use frontend fetch for branch dropdown component (#25719) + * Add open/closed field support for issue index (#25708) + * Some less naked returns (#25682) + * Fix inconsistent user profile layout across tabs (#25625) + * Get latest commit statuses from database instead of git data on dashboard for repositories (#25605) + * Adding branch-name copy to clipboard branches screen. (#25596) + * Update emoji set to Unicode 15 (#25595) + * Move some files under repo/setting (#25585) + * Add custom ansi colors and CSS variables for them (#25546) + * Add log line anchor for action logs (#25532) + * Use flex instead of float for sort button and search input (#25519) + * Update octicons and use `octicon-file-directory-symlink` (#25453) + * Add toasts to UI (#25449) + * Fine tune project board label colors and modal content background (#25419) + * Import additional secrets via file uri (#25408) + * Switch to ansi_up for ansi rendering in actions (#25401) + * Store and use seconds for timeline time comments (#25392) + * Support displaying diff stats in PR tab bar (#25387) + * Use fetch form action for lock/unlock/pin/unpin on sidebar (#25380) + * Refactor: TotalTimes return seconds (#25370) + * Navbar styling rework (#25343) + * Introduce shared template for search inputs (#25338) + * Only show 'Manage Account Links' when necessary (#25311) + * Improve 'Privacy' section in profile settings (#25309) + * Substitute variables in path names of template repos too (#25294) + * Fix tags line no margin see #25255 (#25280) + * Use fetch to send requests to create issues/comments (#25258) + * Change form actions to fetch for submit review box (#25219) + * Improve AJAX link and modal confirm dialog (#25210) + * Reduce unnecessary DB queries for Actions tasks (#25199) + * Disable `Create column` button while the column name is empty (#25192) + * Refactor indexer (#25174) + * Adjust style for action run list (align icons, adjust padding) (#25170) + * Remove duplicated functions when deleting a branch (#25128) + * Make confusable character warning less jarring (#25069) + * Highlight viewed files differently in the PR filetree (#24956) + * Support changing labels of Actions runner without re-registration (#24806) + * Fix duplicate Reviewed-by trailers (#24796) + * Resolve issue with sort icons on admin/users and admin/runners (#24360) + * Split lfs size from repository size (#22900) + * Sync branches into databases (#22743) + * Disable run user change in installation page (#22499) + * Add merge files files to GetCommitFileStatus (#20515) + * Show OpenID Connect and OAuth on signup page (#20242) +* SECURITY + * Dont leak private users via extensions (#28023) (#28029) + * Expanded minimum RSA Keylength to 3072 (#26604) +* TESTING + * Add user secrets API integration tests (#27832) (#27852) + * Add tests for db indexer in indexer_test.go (#27087) + * Speed up TestEventSourceManagerRun (#26262) + * Add unit test for user renaming (#26261) + * Add some Wiki unit tests (#26260) + * Improve unit test for caching (#26185) + * Add unit test for `HashAvatar` (#25662) +* TRANSLATION + * Backport translations to v1.21 (#27899) + * Fix issues in translation file (#27699) (#27737) + * Add locale for deleted head branch (#26296) + * Improve multiple strings in en-US locale (#26213) + * Fix broken translations for package documantion (#25742) + * Correct translation wrong format (#25643) +* BUILD + * Dockerfile small refactor (#27757) (#27826) + * Fix build errors on BSD (in BSDMakefile) (#27594) (#27608) + * Fully replace drone with actions (#27556) (#27575) + * Enable markdownlint `no-duplicate-header` (#27500) (#27506) + * Enable production source maps for index.js, fix CSS sourcemaps (#27291) (#27295) + * Update snap package (#27021) + * Bump go to 1.21 (#26608) + * Bump xgo to go-1.21.x and node to 20 in release-version (#26589) + * Add template linting via djlint (#25212) +* DOCS + * Change default size of issue/pr attachments and repo file (#27946) (#28017) + * Remove `known issue` section in Gitea Actions Doc (#27930) (#27938) + * Remove outdated paragraphs when comparing Gitea Actions to GitHub Actions (#27119) + * Update brew installation documentation since gitea moved to brew core package (#27070) + * Actions are no longer experimental, so enable them by default (#27054) + * Add a documentation note for Windows Service (#26938) + * Add sparse url in cargo package guide (#26937) + * Update nginx recommendations (#26924) + * Update backup instructions to align with archive structure (#26902) + * Expanding documentation in queue.go (#26889) + * Update info regarding internet connection for build (#26776) + * Docs: template variables (#26547) + * Update index doc (#26455) + * Update zh-cn documentation (#26406) + * Fix typos and grammer problems for actions documentation (#26328) + * Update documentation for 1.21 actions (#26317) + * Doc update swagger doc for POST /orgs/{org}/teams (#26155) + * Doc sync authentication.md to zh-cn (#26117) + * Doc guide the user to create the appropriate level runner (#26091) + * Make organization redirect warning more clear (#26077) + * Update blog links (#25843) + * Fix default value for LocalURL (#25426) + * Update `from-source.zh-cn.md` & `from-source.en-us.md` - Cross Compile Using Zig (#25194) +* MISC + * Replace deprecated `elliptic.Marshal` (#26800) + * Add elapsed time on debug for slow git commands (#25642) + ## [1.20.5](https://github.com/go-gitea/gitea/releases/tag/v1.20.5) - 2023-10-03 * ENHANCEMENTS @@ -455,7 +903,6 @@ been added to each release, please refer to the [blog](https://blog.gitea.com). * Add option to search for users is active join a team (#24093) * Add PDF rendering via PDFObject (#24086) * Refactor web route (#24080) - * Make more functions use ctx instead of db.DefaultContext (#24068) * Make HTML template functions support context (#24056) * Refactor rename user and rename organization (#24052) * Localize milestone related time strings (#24051) From d4d05f9f1b0e382ad9b7a53ea8c8e0e9afc7b709 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 14 Nov 2023 15:03:49 +0100 Subject: [PATCH 008/753] Fix release link in changelog for v1.21.0 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f81244644..ae87638f1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ This changelog goes through all the changes that have been made in each release without substantial changes to our git log; to see the highlights of what has been added to each release, please refer to the [blog](https://blog.gitea.com). -## [1.21.0](https://github.com/go-gitea/gitea/releases/tag/1.21.0) - 2023-11-14 +## [1.21.0](https://github.com/go-gitea/gitea/releases/tag/v1.21.0) - 2023-11-14 * BREAKING * Restrict certificate type for builtin SSH server (#26789) From 5ab3782f111dfc10378fce403ea5934c4585c2a9 Mon Sep 17 00:00:00 2001 From: 6543 Date: Tue, 14 Nov 2023 15:23:04 +0100 Subject: [PATCH 009/753] Restricted users only see repos in orgs which their team was assigned to (#28025) --- *Sponsored by Kithara Software GmbH* --- models/repo/repo_list.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/models/repo/repo_list.go b/models/repo/repo_list.go index 1668c23c77..533ca5251f 100644 --- a/models/repo/repo_list.go +++ b/models/repo/repo_list.go @@ -652,12 +652,12 @@ func AccessibleRepositoryCondition(user *user_model.User, unitType unit.Type) bu userOrgTeamUnitRepoCond("`repository`.id", user.ID, unitType), ) } - cond = cond.Or( - // 4. Repositories that we directly own - builder.Eq{"`repository`.owner_id": user.ID}, + // 4. Repositories that we directly own + cond = cond.Or(builder.Eq{"`repository`.owner_id": user.ID}) + if !user.IsRestricted { // 5. Be able to see all public repos in private organizations that we are an org_user of - userOrgPublicRepoCond(user.ID), - ) + cond = cond.Or(userOrgPublicRepoCond(user.ID)) + } } return cond From f65977df3a65e193995c0bdf7069553fd5867fe2 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 14 Nov 2023 23:03:56 +0800 Subject: [PATCH 010/753] Revert "packages: Calculate package size quota using package creator ID instead of owner ID (#28007)" (#28049) This reverts commit #28007 60522fc96f1fa4675e95010e4b1535e0eac21910. --- models/packages/package_file.go | 12 ------------ services/packages/packages.go | 4 +++- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/models/packages/package_file.go b/models/packages/package_file.go index a2ddae7325..1c2c9ac072 100644 --- a/models/packages/package_file.go +++ b/models/packages/package_file.go @@ -230,15 +230,3 @@ func CalculateFileSize(ctx context.Context, opts *PackageFileSearchOptions) (int Join("INNER", "package_blob", "package_blob.id = package_file.blob_id"). SumInt(new(PackageBlob), "size") } - -// CalculateCreatorPackageQuota sums up all blob sizes related to package -// version creator id. -// It does NOT respect the deduplication of blobs. -func CalculateCreatorPackageQuota(ctx context.Context, creatorID int64) (int64, error) { - return db.GetEngine(ctx). - Table("package_version"). - Where(builder.Eq{"creator_id": creatorID}). - Join("INNER", "package_file", "package_version.id = package_file.version_id"). - Join("INNER", "package_blob", "package_blob.id = package_file.blob_id"). - SumInt(new(PackageBlob), "size") -} diff --git a/services/packages/packages.go b/services/packages/packages.go index 294ee6cc1a..56d5cc04de 100644 --- a/services/packages/packages.go +++ b/services/packages/packages.go @@ -401,7 +401,9 @@ func CheckSizeQuotaExceeded(ctx context.Context, doer, owner *user_model.User, p } if setting.Packages.LimitTotalOwnerSize > -1 { - totalSize, err := packages_model.CalculateCreatorPackageQuota(ctx, doer.ID) + totalSize, err := packages_model.CalculateFileSize(ctx, &packages_model.PackageFileSearchOptions{ + OwnerID: owner.ID, + }) if err != nil { log.Error("CalculateFileSize failed: %v", err) return err From 79394b340d227182f94bae48cb08a091c78f2ea2 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Wed, 15 Nov 2023 22:02:46 +0800 Subject: [PATCH 011/753] Improve graceful manager code/comment (#28063) The graceful manager has some bugs (#27643, #28062). This is a preparation for further fixes. --- modules/graceful/context.go | 7 ++++ modules/graceful/manager.go | 52 +++++------------------------ modules/graceful/manager_unix.go | 4 ++- modules/graceful/manager_windows.go | 4 ++- modules/graceful/net_unix.go | 8 ++--- modules/graceful/net_windows.go | 4 +-- modules/graceful/server.go | 26 ++------------- modules/graceful/server_http.go | 7 ++-- 8 files changed, 29 insertions(+), 83 deletions(-) diff --git a/modules/graceful/context.go b/modules/graceful/context.go index 4fcbcb04b6..c9c4ca4e67 100644 --- a/modules/graceful/context.go +++ b/modules/graceful/context.go @@ -7,6 +7,13 @@ import ( "context" ) +// Shutdown procedure: +// * cancel ShutdownContext: the registered context consumers have time to do their cleanup (they could use the hammer context) +// * cancel HammerContext: the all context consumers have limited time to do their cleanup (wait for a few seconds) +// * cancel TerminateContext: the registered context consumers have time to do their cleanup (but they shouldn't use shutdown/hammer context anymore) +// * cancel manager context +// If the shutdown is triggered again during the shutdown procedure, the hammer context will be canceled immediately to force to shut down. + // ShutdownContext returns a context.Context that is Done at shutdown // Callers using this context should ensure that they are registered as a running server // in order that they are waited for. diff --git a/modules/graceful/manager.go b/modules/graceful/manager.go index 068de21076..f3f412863a 100644 --- a/modules/graceful/manager.go +++ b/modules/graceful/manager.go @@ -39,10 +39,10 @@ type RunCanceler interface { // and add a function to call manager.InformCleanup if it's not going to be used const numberOfServersToCreate = 4 -// Manager represents the graceful server manager interface -var manager *Manager - -var initOnce = sync.Once{} +var ( + manager *Manager + initOnce sync.Once +) // GetManager returns the Manager func GetManager() *Manager { @@ -147,12 +147,12 @@ func (g *Manager) doShutdown() { go g.doHammerTime(setting.GracefulHammerTime) } go func() { - g.WaitForServers() + g.runningServerWaitGroup.Wait() // Mop up any remaining unclosed events. g.doHammerTime(0) <-time.After(1 * time.Second) g.doTerminate() - g.WaitForTerminate() + g.terminateWaitGroup.Wait() g.lock.Lock() g.managerCtxCancel() g.lock.Unlock() @@ -199,26 +199,18 @@ func (g *Manager) IsChild() bool { } // IsShutdown returns a channel which will be closed at shutdown. -// The order of closure is IsShutdown, IsHammer (potentially), IsTerminate +// The order of closure is shutdown, hammer (potentially), terminate func (g *Manager) IsShutdown() <-chan struct{} { return g.shutdownCtx.Done() } -// IsHammer returns a channel which will be closed at hammer -// The order of closure is IsShutdown, IsHammer (potentially), IsTerminate +// IsHammer returns a channel which will be closed at hammer. // Servers running within the running server wait group should respond to IsHammer // if not shutdown already func (g *Manager) IsHammer() <-chan struct{} { return g.hammerCtx.Done() } -// IsTerminate returns a channel which will be closed at terminate -// The order of closure is IsShutdown, IsHammer (potentially), IsTerminate -// IsTerminate will only close once all running servers have stopped -func (g *Manager) IsTerminate() <-chan struct{} { - return g.terminateCtx.Done() -} - // ServerDone declares a running server done and subtracts one from the // running server wait group. Users probably do not want to call this // and should use one of the RunWithShutdown* functions @@ -226,28 +218,7 @@ func (g *Manager) ServerDone() { g.runningServerWaitGroup.Done() } -// WaitForServers waits for all running servers to finish. Users should probably -// instead use AtTerminate or IsTerminate -func (g *Manager) WaitForServers() { - g.runningServerWaitGroup.Wait() -} - -// WaitForTerminate waits for all terminating actions to finish. -// Only the main go-routine should use this -func (g *Manager) WaitForTerminate() { - g.terminateWaitGroup.Wait() -} - -func (g *Manager) getState() state { - g.lock.RLock() - defer g.lock.RUnlock() - return g.state -} - func (g *Manager) setStateTransition(old, new state) bool { - if old != g.getState() { - return false - } g.lock.Lock() if g.state != old { g.lock.Unlock() @@ -258,13 +229,6 @@ func (g *Manager) setStateTransition(old, new state) bool { return true } -func (g *Manager) setState(st state) { - g.lock.Lock() - defer g.lock.Unlock() - - g.state = st -} - // InformCleanup tells the cleanup wait group that we have either taken a listener or will not be taking a listener. // At the moment the total number of servers (numberOfServersToCreate) are pre-defined as a const before global init, // so this function MUST be called if a server is not used. diff --git a/modules/graceful/manager_unix.go b/modules/graceful/manager_unix.go index b1fd6da76d..bdf23a4fde 100644 --- a/modules/graceful/manager_unix.go +++ b/modules/graceful/manager_unix.go @@ -107,7 +107,9 @@ func (g *Manager) start(ctx context.Context) { defer pprof.SetGoroutineLabels(ctx) // Set the running state & handle signals - g.setState(stateRunning) + if !g.setStateTransition(stateInit, stateRunning) { + panic("invalid graceful manager state: transition from init to running failed") + } g.notify(statusMsg("Starting Gitea")) g.notify(pidMsg()) go g.handleSignals(g.managerCtx) diff --git a/modules/graceful/manager_windows.go b/modules/graceful/manager_windows.go index f676f86d04..c2ea5383cc 100644 --- a/modules/graceful/manager_windows.go +++ b/modules/graceful/manager_windows.go @@ -85,7 +85,9 @@ func (g *Manager) start() { g.shutdownRequested = make(chan struct{}) // Set the running state - g.setState(stateRunning) + if !g.setStateTransition(stateInit, stateRunning) { + panic("invalid graceful manager state: transition from init to running failed") + } if skip, _ := strconv.ParseBool(os.Getenv("SKIP_MINWINSVC")); skip { log.Trace("Skipping SVC check as SKIP_MINWINSVC is set") return diff --git a/modules/graceful/net_unix.go b/modules/graceful/net_unix.go index f5af1e3937..4f8c036a69 100644 --- a/modules/graceful/net_unix.go +++ b/modules/graceful/net_unix.go @@ -150,12 +150,8 @@ func CloseProvidedListeners() error { return returnableError } -// DefaultGetListener obtains a listener for the local network address. The network must be -// a stream-oriented network: "tcp", "tcp4", "tcp6", "unix" or "unixpacket". It -// returns an provided net.Listener for the matching network and address, or -// creates a new one using net.Listen. This function can be replaced by changing the -// GetListener variable at the top of this file, for example to listen on an onion service using -// github.com/cretz/bine +// DefaultGetListener obtains a listener for the stream-oriented local network address: +// "tcp", "tcp4", "tcp6", "unix" or "unixpacket". func DefaultGetListener(network, address string) (net.Listener, error) { // Add a deferral to say that we've tried to grab a listener defer GetManager().InformCleanup() diff --git a/modules/graceful/net_windows.go b/modules/graceful/net_windows.go index 15d228d6b6..9667bd4d13 100644 --- a/modules/graceful/net_windows.go +++ b/modules/graceful/net_windows.go @@ -10,9 +10,7 @@ package graceful import "net" // DefaultGetListener obtains a listener for the local network address. -// On windows this is basically just a shim around net.Listen. This function -// can be replaced by changing the GetListener variable at the top of this file, -// for example to listen on an onion service using github.com/cretz/bine +// On windows this is basically just a shim around net.Listen. func DefaultGetListener(network, address string) (net.Listener, error) { // Add a deferral to say that we've tried to grab a listener defer GetManager().InformCleanup() diff --git a/modules/graceful/server.go b/modules/graceful/server.go index bd917828bc..2525a83e77 100644 --- a/modules/graceful/server.go +++ b/modules/graceful/server.go @@ -20,31 +20,11 @@ import ( "code.gitea.io/gitea/modules/setting" ) -var ( - // DefaultReadTimeOut default read timeout - DefaultReadTimeOut time.Duration - // DefaultWriteTimeOut default write timeout - DefaultWriteTimeOut time.Duration - // DefaultMaxHeaderBytes default max header bytes - DefaultMaxHeaderBytes int - // PerWriteWriteTimeout timeout for writes - PerWriteWriteTimeout = 30 * time.Second - // PerWriteWriteTimeoutKbTime is a timeout taking account of how much there is to be written - PerWriteWriteTimeoutKbTime = 10 * time.Second -) - -// GetListener returns a listener from a GetListener function, which must have the -// signature: `func FunctioName(network, address string) (net.Listener, error)`. -// This determines the implementation of net.Listener which the server will use.` -// It is implemented in this way so that downstreams may specify the type of listener -// they want to provide Gitea on by default, such as with a hidden service or a p2p network -// No need to worry about "breaking" if there would be a refactoring for the Listeners. No compatibility-guarantee for this mechanism +// GetListener returns a net listener +// This determines the implementation of net.Listener which the server will use, +// so that downstreams could provide their own Listener, such as with a hidden service or a p2p network var GetListener = DefaultGetListener -func init() { - DefaultMaxHeaderBytes = 0 // use http.DefaultMaxHeaderBytes - which currently is 1 << 20 (1MB) -} - // ServeFunction represents a listen.Accept loop type ServeFunction = func(net.Listener) error diff --git a/modules/graceful/server_http.go b/modules/graceful/server_http.go index a1f8e0ff52..7c855ac64e 100644 --- a/modules/graceful/server_http.go +++ b/modules/graceful/server_http.go @@ -13,11 +13,8 @@ import ( func newHTTPServer(network, address, name string, handler http.Handler) (*Server, ServeFunction) { server := NewServer(network, address, name) httpServer := http.Server{ - ReadTimeout: DefaultReadTimeOut, - WriteTimeout: DefaultWriteTimeOut, - MaxHeaderBytes: DefaultMaxHeaderBytes, - Handler: handler, - BaseContext: func(net.Listener) context.Context { return GetManager().HammerContext() }, + Handler: handler, + BaseContext: func(net.Listener) context.Context { return GetManager().HammerContext() }, } server.OnShutdown = func() { httpServer.SetKeepAlivesEnabled(false) From 49dddd87b19aebe83e1c54a455e62529a19f61b4 Mon Sep 17 00:00:00 2001 From: sebastian-sauer Date: Thu, 16 Nov 2023 04:58:53 +0100 Subject: [PATCH 012/753] Improve PR diff view on mobile (#27883) 1. Show diff stats only on large screens these are already shown in tabs, so no need for this duplicate information on small screens ![image](https://github.com/go-gitea/gitea/assets/1135157/1287839d-7490-42eb-a17e-d526dc0bfd9e) ![image](https://github.com/go-gitea/gitea/assets/1135157/e9dcd89d-ed4d-4945-a7aa-4e6fc6d9c3a2) 2. Hide viewed files information on small screens Github does the same and this gives us more free space on small screens ![image](https://github.com/go-gitea/gitea/assets/1135157/e90b042f-fffb-4f79-a5ae-cd480c9d8334) ![image](https://github.com/go-gitea/gitea/assets/1135157/d2480ffe-58f2-4694-8ae1-a2ab0aae14d4) 3. Review bar now doesn't wrap so we don't need the 77px even on very small screens (the sticky headers are still working) ![image](https://github.com/go-gitea/gitea/assets/1135157/42b19b2b-73ef-4b88-8680-c555879b363b) --- templates/repo/diff/box.tmpl | 2 +- web_src/css/repo.css | 27 ++------------------------- 2 files changed, 3 insertions(+), 26 deletions(-) diff --git a/templates/repo/diff/box.tmpl b/templates/repo/diff/box.tmpl index 945c521a57..e72ac1eeae 100644 --- a/templates/repo/diff/box.tmpl +++ b/templates/repo/diff/box.tmpl @@ -25,7 +25,7 @@
{{if and .PageIsPullFiles $.SignedUserID (not .IsArchived) (not .DiffNotAvailable)}} -
+
diff --git a/web_src/css/repo.css b/web_src/css/repo.css index d759d10c8a..6bddbe9ba5 100644 --- a/web_src/css/repo.css +++ b/web_src/css/repo.css @@ -1506,7 +1506,6 @@ @media (max-width: 991.98px) { .repository .diff-detail-box { flex-direction: row; - height: 77px; /* this height should match sticky-2nd-row */ } } @@ -1534,13 +1533,9 @@ color: var(--color-red); } -@media (max-width: 480px) { +@media (max-width: 991.98px) { .repository .diff-detail-box .diff-detail-stats { - font-size: 0; - line-height: 1.6rem; - } - .repository .diff-detail-box .diff-detail-stats strong { - font-size: 1rem; + display: none !important; } } @@ -1735,12 +1730,6 @@ border: none; } -@media (max-width: 991.98px) { - .diff-file-box { - scroll-margin-top: 77px; /* match .repository .diff-detail-box */ - } -} - /* TODO: this can potentially be made "global" by removing the class prefix */ .diff-file-box .ui.attached.header, .diff-file-box .ui.attached.table { @@ -2826,18 +2815,6 @@ tbody.commit-list { z-index: 7; } -@media (max-width: 991.98px) { - .ui.attached.header.diff-file-header.sticky-2nd-row { - top: 77px; /* match .repository .diff-detail-box */ - } -} - -@media (max-width: 480px) { - .ui.attached.header.diff-file-header.sticky-2nd-row { - position: static; - } -} - .diff-file-name { flex: auto; min-width: 100px; From fce1d5d7dce6a16429d0fe043555eac2c083ae7b Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Thu, 16 Nov 2023 20:53:42 +0800 Subject: [PATCH 013/753] Fix system config cache expiration timing (#28072) To avoid unnecessary database access, the `cacheTime` should always be set if the revision has been checked. Fix #28057 --- models/system/setting.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/models/system/setting.go b/models/system/setting.go index 1ae6f5c652..507d23cff6 100644 --- a/models/system/setting.go +++ b/models/system/setting.go @@ -115,24 +115,26 @@ func (d *dbConfigCachedGetter) GetValue(ctx context.Context, key string) (v stri func (d *dbConfigCachedGetter) GetRevision(ctx context.Context) int { d.mu.RLock() - defer d.mu.RUnlock() - if time.Since(d.cacheTime) < time.Second { - return d.revision + cachedDuration := time.Since(d.cacheTime) + cachedRevision := d.revision + d.mu.RUnlock() + + if cachedDuration < time.Second { + return cachedRevision } + + d.mu.Lock() + defer d.mu.Unlock() if GetRevision(ctx) != d.revision { - d.mu.RUnlock() - d.mu.Lock() rev, set, err := GetAllSettings(ctx) if err != nil { log.Error("Unable to get all settings: %v", err) } else { - d.cacheTime = time.Now() d.revision = rev d.settings = set } - d.mu.Unlock() - d.mu.RLock() } + d.cacheTime = time.Now() return d.revision } From 17d246cdcc0bf615ee4ba97a17c0f7e2c2f5f27f Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 17 Nov 2023 10:30:57 +0800 Subject: [PATCH 014/753] Fix incorrect pgsql conn builder behavior (#28085) Fix #28083 and fix the tests --- modules/setting/database.go | 5 +++-- modules/setting/database_test.go | 15 ++++++++------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/modules/setting/database.go b/modules/setting/database.go index aa42f506bc..761e767e8f 100644 --- a/modules/setting/database.go +++ b/modules/setting/database.go @@ -109,7 +109,7 @@ func DBConnStr() (string, error) { connStr = fmt.Sprintf("%s:%s@%s(%s)/%s%scharset=%s&parseTime=true&tls=%s", Database.User, Database.Passwd, connType, Database.Host, Database.Name, paramSep, Database.MysqlCharset, tls) case "postgres": - connStr = getPostgreSQLConnectionString(Database.Host, Database.User, Database.Passwd, Database.Name, paramSep, Database.SSLMode) + connStr = getPostgreSQLConnectionString(Database.Host, Database.User, Database.Passwd, Database.Name, Database.SSLMode) case "mssql": host, port := ParseMSSQLHostPort(Database.Host) connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, Database.Name, Database.User, Database.Passwd) @@ -157,7 +157,8 @@ func parsePostgreSQLHostPort(info string) (host, port string) { return host, port } -func getPostgreSQLConnectionString(dbHost, dbUser, dbPasswd, dbName, dbParam, dbsslMode string) (connStr string) { +func getPostgreSQLConnectionString(dbHost, dbUser, dbPasswd, dbName, dbsslMode string) (connStr string) { + dbName, dbParam, _ := strings.Cut(dbName, "?") host, port := parsePostgreSQLHostPort(dbHost) connURL := url.URL{ Scheme: "postgres", diff --git a/modules/setting/database_test.go b/modules/setting/database_test.go index 85271c36cb..1d5b416504 100644 --- a/modules/setting/database_test.go +++ b/modules/setting/database_test.go @@ -59,38 +59,39 @@ func Test_parsePostgreSQLHostPort(t *testing.T) { func Test_getPostgreSQLConnectionString(t *testing.T) { tests := []struct { Host string - Port string User string Passwd string Name string - Param string SSLMode string Output string }{ { Host: "/tmp/pg.sock", - Port: "4321", User: "testuser", Passwd: "space space !#$%^^%^```-=?=", Name: "gitea", - Param: "", SSLMode: "false", Output: "postgres://testuser:space%20space%20%21%23$%25%5E%5E%25%5E%60%60%60-=%3F=@:5432/gitea?host=%2Ftmp%2Fpg.sock&sslmode=false", }, { Host: "localhost", - Port: "1234", User: "pgsqlusername", Passwd: "I love Gitea!", Name: "gitea", - Param: "", SSLMode: "true", Output: "postgres://pgsqlusername:I%20love%20Gitea%21@localhost:5432/gitea?sslmode=true", }, + { + Host: "localhost:1234", + User: "user", + Passwd: "pass", + Name: "gitea?param=1", + Output: "postgres://user:pass@localhost:1234/gitea?param=1&sslmode=", + }, } for _, test := range tests { - connStr := getPostgreSQLConnectionString(test.Host, test.User, test.Passwd, test.Name, test.Param, test.SSLMode) + connStr := getPostgreSQLConnectionString(test.Host, test.User, test.Passwd, test.Name, test.SSLMode) assert.Equal(t, test.Output, connStr) } } From 58f5fa653676fefc9b497e2cc18af976f749273c Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Fri, 17 Nov 2023 12:17:33 +0100 Subject: [PATCH 015/753] Fix Matrix and MSTeams nil dereference (#28089) Fixes #28088 Fixes #28094 Added missing tests. --------- Co-authored-by: Lunny Xiao --- services/webhook/dingtalk_test.go | 15 +++++++++++++++ services/webhook/discord_test.go | 18 ++++++++++++++++++ services/webhook/feishu_test.go | 12 ++++++++++++ services/webhook/general_test.go | 30 ++++++++++++++++++++++++++++++ services/webhook/matrix.go | 6 +++--- services/webhook/matrix_test.go | 13 +++++++++++++ services/webhook/msteams.go | 7 ++++--- services/webhook/msteams_test.go | 27 +++++++++++++++++++++++++++ services/webhook/packagist_test.go | 9 +++++++++ services/webhook/slack_test.go | 12 ++++++++++++ services/webhook/telegram_test.go | 12 ++++++++++++ 11 files changed, 155 insertions(+), 6 deletions(-) diff --git a/services/webhook/dingtalk_test.go b/services/webhook/dingtalk_test.go index 7289c751f3..a03fa46f14 100644 --- a/services/webhook/dingtalk_test.go +++ b/services/webhook/dingtalk_test.go @@ -188,6 +188,21 @@ func TestDingTalkPayload(t *testing.T) { assert.Equal(t, "http://localhost:3000/test/repo", parseRealSingleURL(pl.(*DingtalkPayload).ActionCard.SingleURL)) }) + t.Run("Package", func(t *testing.T) { + p := packageTestPayload() + + d := new(DingtalkPayload) + pl, err := d.Package(p) + require.NoError(t, err) + require.NotNil(t, pl) + require.IsType(t, &DingtalkPayload{}, pl) + + assert.Equal(t, "Package created: GiteaContainer:latest by user1", pl.(*DingtalkPayload).ActionCard.Text) + assert.Equal(t, "Package created: GiteaContainer:latest by user1", pl.(*DingtalkPayload).ActionCard.Title) + assert.Equal(t, "view package", pl.(*DingtalkPayload).ActionCard.SingleTitle) + assert.Equal(t, "http://localhost:3000/user1/-/packages/container/GiteaContainer/latest", parseRealSingleURL(pl.(*DingtalkPayload).ActionCard.SingleURL)) + }) + t.Run("Wiki", func(t *testing.T) { p := wikiTestPayload() diff --git a/services/webhook/discord_test.go b/services/webhook/discord_test.go index 6a276e9e87..b567cbc395 100644 --- a/services/webhook/discord_test.go +++ b/services/webhook/discord_test.go @@ -211,6 +211,24 @@ func TestDiscordPayload(t *testing.T) { assert.Equal(t, p.Sender.AvatarURL, pl.(*DiscordPayload).Embeds[0].Author.IconURL) }) + t.Run("Package", func(t *testing.T) { + p := packageTestPayload() + + d := new(DiscordPayload) + pl, err := d.Package(p) + require.NoError(t, err) + require.NotNil(t, pl) + require.IsType(t, &DiscordPayload{}, pl) + + assert.Len(t, pl.(*DiscordPayload).Embeds, 1) + assert.Equal(t, "Package created: GiteaContainer:latest", pl.(*DiscordPayload).Embeds[0].Title) + assert.Empty(t, pl.(*DiscordPayload).Embeds[0].Description) + assert.Equal(t, "http://localhost:3000/user1/-/packages/container/GiteaContainer/latest", pl.(*DiscordPayload).Embeds[0].URL) + assert.Equal(t, p.Sender.UserName, pl.(*DiscordPayload).Embeds[0].Author.Name) + assert.Equal(t, setting.AppURL+p.Sender.UserName, pl.(*DiscordPayload).Embeds[0].Author.URL) + assert.Equal(t, p.Sender.AvatarURL, pl.(*DiscordPayload).Embeds[0].Author.IconURL) + }) + t.Run("Wiki", func(t *testing.T) { p := wikiTestPayload() diff --git a/services/webhook/feishu_test.go b/services/webhook/feishu_test.go index a3182e82b0..98bc50dede 100644 --- a/services/webhook/feishu_test.go +++ b/services/webhook/feishu_test.go @@ -144,6 +144,18 @@ func TestFeishuPayload(t *testing.T) { assert.Equal(t, "[test/repo] Repository created", pl.(*FeishuPayload).Content.Text) }) + t.Run("Package", func(t *testing.T) { + p := packageTestPayload() + + d := new(FeishuPayload) + pl, err := d.Package(p) + require.NoError(t, err) + require.NotNil(t, pl) + require.IsType(t, &FeishuPayload{}, pl) + + assert.Equal(t, "Package created: GiteaContainer:latest by user1", pl.(*FeishuPayload).Content.Text) + }) + t.Run("Wiki", func(t *testing.T) { p := wikiTestPayload() diff --git a/services/webhook/general_test.go b/services/webhook/general_test.go index a9a8c6b521..41bac3fd04 100644 --- a/services/webhook/general_test.go +++ b/services/webhook/general_test.go @@ -303,6 +303,36 @@ func repositoryTestPayload() *api.RepositoryPayload { } } +func packageTestPayload() *api.PackagePayload { + return &api.PackagePayload{ + Action: api.HookPackageCreated, + Sender: &api.User{ + UserName: "user1", + AvatarURL: "http://localhost:3000/user1/avatar", + }, + Repository: nil, + Organization: &api.User{ + UserName: "org1", + AvatarURL: "http://localhost:3000/org1/avatar", + }, + Package: &api.Package{ + Owner: &api.User{ + UserName: "user1", + AvatarURL: "http://localhost:3000/user1/avatar", + }, + Repository: nil, + Creator: &api.User{ + UserName: "user1", + AvatarURL: "http://localhost:3000/user1/avatar", + }, + Type: "container", + Name: "GiteaContainer", + Version: "latest", + HTMLURL: "http://localhost:3000/user1/-/packages/container/GiteaContainer/latest", + }, + } +} + func TestGetIssuesPayloadInfo(t *testing.T) { p := issueTestPayload() diff --git a/services/webhook/matrix.go b/services/webhook/matrix.go index ab7e6b72c2..602d16ef39 100644 --- a/services/webhook/matrix.go +++ b/services/webhook/matrix.go @@ -212,14 +212,14 @@ func (m *MatrixPayload) Repository(p *api.RepositoryPayload) (api.Payloader, err func (m *MatrixPayload) Package(p *api.PackagePayload) (api.Payloader, error) { senderLink := MatrixLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName) - repoLink := MatrixLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName) + packageLink := MatrixLinkFormatter(p.Package.HTMLURL, p.Package.Name) var text string switch p.Action { case api.HookPackageCreated: - text = fmt.Sprintf("[%s] Package published by %s", repoLink, senderLink) + text = fmt.Sprintf("[%s] Package published by %s", packageLink, senderLink) case api.HookPackageDeleted: - text = fmt.Sprintf("[%s] Package deleted by %s", repoLink, senderLink) + text = fmt.Sprintf("[%s] Package deleted by %s", packageLink, senderLink) } return getMatrixPayload(text, nil, m.MsgType), nil diff --git a/services/webhook/matrix_test.go b/services/webhook/matrix_test.go index 8c71094228..99a22fbd7e 100644 --- a/services/webhook/matrix_test.go +++ b/services/webhook/matrix_test.go @@ -155,6 +155,19 @@ func TestMatrixPayload(t *testing.T) { assert.Equal(t, `[test/repo] Repository created by user1`, pl.(*MatrixPayload).FormattedBody) }) + t.Run("Package", func(t *testing.T) { + p := packageTestPayload() + + d := new(MatrixPayload) + pl, err := d.Package(p) + require.NoError(t, err) + require.NotNil(t, pl) + require.IsType(t, &MatrixPayload{}, pl) + + assert.Equal(t, `[[GiteaContainer](http://localhost:3000/user1/-/packages/container/GiteaContainer/latest)] Package published by [user1](https://try.gitea.io/user1)`, pl.(*MatrixPayload).Body) + assert.Equal(t, `[GiteaContainer] Package published by user1`, pl.(*MatrixPayload).FormattedBody) + }) + t.Run("Wiki", func(t *testing.T) { p := wikiTestPayload() diff --git a/services/webhook/msteams.go b/services/webhook/msteams.go index f58da3fe1c..37810b4cd3 100644 --- a/services/webhook/msteams.go +++ b/services/webhook/msteams.go @@ -316,11 +316,12 @@ func GetMSTeamsPayload(p api.Payloader, event webhook_module.HookEventType, _ st } func createMSTeamsPayload(r *api.Repository, s *api.User, title, text, actionTarget string, color int, fact *MSTeamsFact) *MSTeamsPayload { - facts := []MSTeamsFact{ - { + facts := make([]MSTeamsFact, 0, 2) + if r != nil { + facts = append(facts, MSTeamsFact{ Name: "Repository:", Value: r.FullName, - }, + }) } if fact != nil { facts = append(facts, *fact) diff --git a/services/webhook/msteams_test.go b/services/webhook/msteams_test.go index 990a535df5..8d1aed6040 100644 --- a/services/webhook/msteams_test.go +++ b/services/webhook/msteams_test.go @@ -329,6 +329,33 @@ func TestMSTeamsPayload(t *testing.T) { assert.Equal(t, "http://localhost:3000/test/repo", pl.(*MSTeamsPayload).PotentialAction[0].Targets[0].URI) }) + t.Run("Package", func(t *testing.T) { + p := packageTestPayload() + + d := new(MSTeamsPayload) + pl, err := d.Package(p) + require.NoError(t, err) + require.NotNil(t, pl) + require.IsType(t, &MSTeamsPayload{}, pl) + + assert.Equal(t, "Package created: GiteaContainer:latest", pl.(*MSTeamsPayload).Title) + assert.Equal(t, "Package created: GiteaContainer:latest", pl.(*MSTeamsPayload).Summary) + assert.Len(t, pl.(*MSTeamsPayload).Sections, 1) + assert.Equal(t, "user1", pl.(*MSTeamsPayload).Sections[0].ActivitySubtitle) + assert.Empty(t, pl.(*MSTeamsPayload).Sections[0].Text) + assert.Len(t, pl.(*MSTeamsPayload).Sections[0].Facts, 1) + for _, fact := range pl.(*MSTeamsPayload).Sections[0].Facts { + if fact.Name == "Package:" { + assert.Equal(t, p.Package.Name, fact.Value) + } else { + t.Fail() + } + } + assert.Len(t, pl.(*MSTeamsPayload).PotentialAction, 1) + assert.Len(t, pl.(*MSTeamsPayload).PotentialAction[0].Targets, 1) + assert.Equal(t, "http://localhost:3000/user1/-/packages/container/GiteaContainer/latest", pl.(*MSTeamsPayload).PotentialAction[0].Targets[0].URI) + }) + t.Run("Wiki", func(t *testing.T) { p := wikiTestPayload() diff --git a/services/webhook/packagist_test.go b/services/webhook/packagist_test.go index 932b56fe9b..26d01b0555 100644 --- a/services/webhook/packagist_test.go +++ b/services/webhook/packagist_test.go @@ -115,6 +115,15 @@ func TestPackagistPayload(t *testing.T) { require.Nil(t, pl) }) + t.Run("Package", func(t *testing.T) { + p := packageTestPayload() + + d := new(PackagistPayload) + pl, err := d.Package(p) + require.NoError(t, err) + require.Nil(t, pl) + }) + t.Run("Wiki", func(t *testing.T) { p := wikiTestPayload() diff --git a/services/webhook/slack_test.go b/services/webhook/slack_test.go index d9828f374f..b1340963e2 100644 --- a/services/webhook/slack_test.go +++ b/services/webhook/slack_test.go @@ -144,6 +144,18 @@ func TestSlackPayload(t *testing.T) { assert.Equal(t, "[] Repository created by ", pl.(*SlackPayload).Text) }) + t.Run("Package", func(t *testing.T) { + p := packageTestPayload() + + d := new(SlackPayload) + pl, err := d.Package(p) + require.NoError(t, err) + require.NotNil(t, pl) + require.IsType(t, &SlackPayload{}, pl) + + assert.Equal(t, "Package created: by ", pl.(*SlackPayload).Text) + }) + t.Run("Wiki", func(t *testing.T) { p := wikiTestPayload() diff --git a/services/webhook/telegram_test.go b/services/webhook/telegram_test.go index b42b0ccda8..5b9927d057 100644 --- a/services/webhook/telegram_test.go +++ b/services/webhook/telegram_test.go @@ -144,6 +144,18 @@ func TestTelegramPayload(t *testing.T) { assert.Equal(t, `[test/repo] Repository created`, pl.(*TelegramPayload).Message) }) + t.Run("Package", func(t *testing.T) { + p := packageTestPayload() + + d := new(TelegramPayload) + pl, err := d.Package(p) + require.NoError(t, err) + require.NotNil(t, pl) + require.IsType(t, &TelegramPayload{}, pl) + + assert.Equal(t, `Package created: GiteaContainer:latest by user1`, pl.(*TelegramPayload).Message) + }) + t.Run("Wiki", func(t *testing.T) { p := wikiTestPayload() From f63b1166970705454f62059cf46f3fbc6f0c8871 Mon Sep 17 00:00:00 2001 From: Nanguan Lin <70063547+lng2020@users.noreply.github.com> Date: Fri, 17 Nov 2023 19:42:00 +0800 Subject: [PATCH 016/753] Change default size of attachments and repo files (#28100) https://github.com/go-gitea/gitea/pull/27946 forgets to change them in code. Sorry about that. --- modules/setting/attachment.go | 2 +- modules/setting/repository.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/setting/attachment.go b/modules/setting/attachment.go index 491564c9dc..007aae9d04 100644 --- a/modules/setting/attachment.go +++ b/modules/setting/attachment.go @@ -13,7 +13,7 @@ var Attachment = struct { }{ Storage: &Storage{}, AllowedTypes: ".csv,.docx,.fodg,.fodp,.fods,.fodt,.gif,.gz,.jpeg,.jpg,.log,.md,.mov,.mp4,.odf,.odg,.odp,.ods,.odt,.patch,.pdf,.png,.pptx,.svg,.tgz,.txt,.webm,.xls,.xlsx,.zip", - MaxSize: 4, + MaxSize: 2048, MaxFiles: 5, Enabled: true, } diff --git a/modules/setting/repository.go b/modules/setting/repository.go index 42ffb99138..9697a851d3 100644 --- a/modules/setting/repository.go +++ b/modules/setting/repository.go @@ -184,7 +184,7 @@ var ( Enabled: true, TempPath: "data/tmp/uploads", AllowedTypes: "", - FileMaxSize: 3, + FileMaxSize: 50, MaxFiles: 5, }, From e31c6cfe6e30341c502302d1c0a03138f8bf5c9f Mon Sep 17 00:00:00 2001 From: sebastian-sauer Date: Fri, 17 Nov 2023 19:35:51 +0100 Subject: [PATCH 017/753] Fix Show/hide filetree button on small displays (#27881) the gt-df's display:flex !important did override the display:none on small displays --------- Co-authored-by: wxiaoguang --- templates/repo/diff/box.tmpl | 4 ++-- web_src/css/repo.css | 20 -------------------- 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/templates/repo/diff/box.tmpl b/templates/repo/diff/box.tmpl index e72ac1eeae..1224bbe84c 100644 --- a/templates/repo/diff/box.tmpl +++ b/templates/repo/diff/box.tmpl @@ -3,7 +3,7 @@
{{if $showFileTree}} -
diff --git a/templates/admin/emails/list.tmpl b/templates/admin/emails/list.tmpl index 84afc0585f..bcd80368e6 100644 --- a/templates/admin/emails/list.tmpl +++ b/templates/admin/emails/list.tmpl @@ -7,7 +7,7 @@