From 67a9416ae55ea765e3f405e00d89b0b8f3899330 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Thu, 12 Feb 2015 12:38:44 -0500 Subject: [PATCH 01/30] templates/user/auth/signin.tmpl: hide sign up prompt when registration is disabled #884 --- gogs.go | 2 +- models/models.go | 8 ++++---- templates/.VERSION | 2 +- templates/user/auth/signin.tmpl | 2 ++ 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/gogs.go b/gogs.go index eac593621..76c6c71fc 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.5.13.0211 Beta" +const APP_VER = "0.5.13.0212 Beta" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/models.go b/models/models.go index 3eeeabda3..35e803834 100644 --- a/models/models.go +++ b/models/models.go @@ -15,7 +15,7 @@ import ( "github.com/go-xorm/xorm" _ "github.com/lib/pq" - "github.com/gogits/gogs/models/migrations" + // "github.com/gogits/gogs/models/migrations" "github.com/gogits/gogs/modules/setting" ) @@ -136,9 +136,9 @@ func NewEngine() (err error) { return err } - if err = migrations.Migrate(x); err != nil { - return err - } + // if err = migrations.Migrate(x); err != nil { + // return err + // } if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil { return fmt.Errorf("sync database struct error: %v\n", err) diff --git a/templates/.VERSION b/templates/.VERSION index 2aad3653c..6d13155b0 100644 --- a/templates/.VERSION +++ b/templates/.VERSION @@ -1 +1 @@ -0.5.13.0211 Beta \ No newline at end of file +0.5.13.0212 Beta \ No newline at end of file diff --git a/templates/user/auth/signin.tmpl b/templates/user/auth/signin.tmpl index 78d6febb8..455df63ac 100644 --- a/templates/user/auth/signin.tmpl +++ b/templates/user/auth/signin.tmpl @@ -26,10 +26,12 @@      {{if not .IsSocialLogin}}{{.i18n.Tr "auth.forget_password"}}{{end}} + {{if .ShowRegistrationButton}}
{{.i18n.Tr "auth.sign_up_now" | Str2html}}
+ {{end}} {{if and (not .IsSocialLogin) .OauthEnabled}}
From def39d191b7764994b6843491a64123ae5a6ffa9 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Fri, 13 Feb 2015 15:48:10 -0500 Subject: [PATCH 02/30] conf/locale: update all locales --- conf/locale/locale_de-DE.ini | 1 + conf/locale/locale_es-ES.ini | 1 + conf/locale/locale_fr-CA.ini | 1 + conf/locale/locale_ja-JP.ini | 1 + conf/locale/locale_lv-LV.ini | 1 + conf/locale/locale_nl-NL.ini | 5 +++-- conf/locale/locale_ru-RU.ini | 19 ++++++++++--------- conf/locale/locale_zh-CN.ini | 1 + conf/locale/locale_zh-HK.ini | 1 + 9 files changed, 20 insertions(+), 11 deletions(-) diff --git a/conf/locale/locale_de-DE.ini b/conf/locale/locale_de-DE.ini index 1dc7523b0..31ee931b9 100755 --- a/conf/locale/locale_de-DE.ini +++ b/conf/locale/locale_de-DE.ini @@ -647,6 +647,7 @@ config.reset_password_code_lives=Passwortcode Lebensdauer config.webhook_config=Webhook-Einstellungen config.task_interval=Task-Intervall config.deliver_timeout=Zeitlimit für Zustellung +config.skip_tls_verify=Skip TLS Verify config.mailer_config=Mailer-Einstellungen config.mailer_enabled=Aktiviert config.mailer_name=Name diff --git a/conf/locale/locale_es-ES.ini b/conf/locale/locale_es-ES.ini index d7fab5f96..046bab896 100755 --- a/conf/locale/locale_es-ES.ini +++ b/conf/locale/locale_es-ES.ini @@ -647,6 +647,7 @@ config.reset_password_code_lives=Reset Password Code Lives config.webhook_config=Webhook Configuration config.task_interval=Task Interval config.deliver_timeout=Deliver Timeout +config.skip_tls_verify=Skip TLS Verify config.mailer_config=Mailer Configuration config.mailer_enabled=Enabled config.mailer_name=Name diff --git a/conf/locale/locale_fr-CA.ini b/conf/locale/locale_fr-CA.ini index 94a2e9686..0aeae3423 100755 --- a/conf/locale/locale_fr-CA.ini +++ b/conf/locale/locale_fr-CA.ini @@ -647,6 +647,7 @@ config.reset_password_code_lives=Réinitialiser le Mot De Passe des Limites de C config.webhook_config=Configuration Webhook config.task_interval=Intervalles de Tâches config.deliver_timeout=Expiration d'Envoi +config.skip_tls_verify=Skip TLS Verify config.mailer_config=Configuration du Maileur config.mailer_enabled=Activé config.mailer_name=Nom diff --git a/conf/locale/locale_ja-JP.ini b/conf/locale/locale_ja-JP.ini index 29ea94e4d..441da8feb 100755 --- a/conf/locale/locale_ja-JP.ini +++ b/conf/locale/locale_ja-JP.ini @@ -647,6 +647,7 @@ config.reset_password_code_lives=パスワードリンクの有効期限をリ config.webhook_config=Webhook設定 config.task_interval=タスクの間隔 config.deliver_timeout=送信タイムアウト +config.skip_tls_verify=TLSの確認を省略 config.mailer_config=メーラーの構成 config.mailer_enabled=有効にした config.mailer_name=名前 diff --git a/conf/locale/locale_lv-LV.ini b/conf/locale/locale_lv-LV.ini index 6ab814806..b640972c8 100755 --- a/conf/locale/locale_lv-LV.ini +++ b/conf/locale/locale_lv-LV.ini @@ -647,6 +647,7 @@ config.reset_password_code_lives=Paroles atiestatīšanas koda ilgums config.webhook_config=Tīkla āķu konfigurācija config.task_interval=Uzdevuma intervāls config.deliver_timeout=Piegādes noildze +config.skip_tls_verify=Skip TLS Verify config.mailer_config=Sūtītāja konfigurācija config.mailer_enabled=Iespējots config.mailer_name=Nosaukums diff --git a/conf/locale/locale_nl-NL.ini b/conf/locale/locale_nl-NL.ini index adc98c9d5..0a4ecb43a 100755 --- a/conf/locale/locale_nl-NL.ini +++ b/conf/locale/locale_nl-NL.ini @@ -516,8 +516,8 @@ dashboard.git_gc_repos=Garbage collectie uitvoeren dashboard.git_gc_repos_success=Garbage collectie met succes uitgevoerd. dashboard.resync_all_sshkeys=Herschrijf '.ssh/authorized_keys' (Let op: alle sleutels die niet van Gogs zijn zullen verloren gaan!) dashboard.resync_all_sshkeys_success=Alle publieke sleutels zijn herschreven. -dashboard.resync_all_update_hooks=Rewrite all update hook of repositories (needed when custom config path is changed) -dashboard.resync_all_update_hooks_success=All repositories' update hook have been rewritten successfully. +dashboard.resync_all_update_hooks=Herschrijf alle repositorie-hooks (nodig als de configuratie bestandslocatie is gewijzigd) +dashboard.resync_all_update_hooks_success=Alle repositorie-hooks zijn herschreven. dashboard.server_uptime=Uptime server dashboard.current_goroutine=Huidige Goroutines @@ -647,6 +647,7 @@ config.reset_password_code_lives=Reset wachtwoord Code leven config.webhook_config=Webhook configuratie config.task_interval=Taakinterval config.deliver_timeout=Bezorging verlooptijd +config.skip_tls_verify=TLS certificaat controle overslaan config.mailer_config=Mailerconfiguatie config.mailer_enabled=Ingeschakeld config.mailer_name=Naam diff --git a/conf/locale/locale_ru-RU.ini b/conf/locale/locale_ru-RU.ini index aa2c0ee55..e21dca14d 100755 --- a/conf/locale/locale_ru-RU.ini +++ b/conf/locale/locale_ru-RU.ini @@ -58,11 +58,11 @@ repo_path_helper=Всех удаленные репозитории Git буде run_user=Пользователь run_user_helper=У пользователя должен быть доступ к пути к корню репозитория и к запуску Gogs. domain=Домен -domain_helper=This affects SSH clone URLs. -http_port=HTTP Port -http_port_helper=Port number which application will listen on. +domain_helper=Влияет на URL-адреса для клонирования по SSH. +http_port=Порт HTTP +http_port_helper=Номер порта, который приложение будет слушать. app_url=URL приложения -app_url_helper=This affects HTTP/HTTPS clone URL and somewhere in e-mail. +app_url_helper=Этот параметр влияет на URL для клонирования по HTTP/HTTPS и на адреса в электронной почте. email_title=Настройки службы электронной почты (опционально) smtp_host=Узел SMTP mailer_user=Электронная почта отправителя @@ -80,7 +80,7 @@ test_git_failed=Не удалось проверить 'git' команду: %v sqlite3_not_available=Ваша версия не поддерживает SQLite3, пожалуйста скачайте официальную бинарную версию от %s, а не версию gobuild. invalid_db_setting=Настройки базы данных не правильные: %v invalid_repo_path=Недопустимый путь к корню репозитория: %v -run_user_not_match=Run user isn't the current user: %s -> %s +run_user_not_match=Текущий пользователь не является пользователем для запуска: %s -> %s save_config_failed=Не удалось сохранить конфигурацию: %v invalid_admin_setting=Указан недопустимый параметр учетной записи администратора: %v install_success=Добро пожаловать! Мы рады, что вы выбрали Gogs. Веселитесь и берегите себя. @@ -88,7 +88,7 @@ install_success=Добро пожаловать! Мы рады, что вы вы [home] uname_holder=Имя пользователь или E-mail password_holder=Пароль -switch_dashboard_context=Switch Dashboard Context +switch_dashboard_context=Переключить контекст панели управления my_repos=Мои репозитории collaborative_repos=Совместные репозитории my_orgs=Моя Организация @@ -280,9 +280,9 @@ license_helper=Выберите файл лицензии init_readme=Создать репозиторий с файлом README.md create_repo=Создание репозитория default_branch=Ветка по умолчанию -mirror_interval=Mirror Interval (hour) -goget_meta=Go-Get Meta -goget_meta_helper=This repository will be Go-Getable +mirror_interval=Интервал зеркалирования (час) +goget_meta=Meta-тег для go get +goget_meta_helper=Репозиторий будет доступен для go get need_auth=Требуется авторизация migrate_type=Тип миграции @@ -647,6 +647,7 @@ config.reset_password_code_lives=Reset Password Code Lives config.webhook_config=Настройка автоматического обновления репозиции config.task_interval=Интервал задания config.deliver_timeout=Задержка доставки +config.skip_tls_verify=Skip TLS Verify config.mailer_config=Настройки почты config.mailer_enabled=Включено config.mailer_name=Имя diff --git a/conf/locale/locale_zh-CN.ini b/conf/locale/locale_zh-CN.ini index efeca15ad..353706822 100755 --- a/conf/locale/locale_zh-CN.ini +++ b/conf/locale/locale_zh-CN.ini @@ -647,6 +647,7 @@ config.reset_password_code_lives=重置密码链接有效期 config.webhook_config=Web 钩子配置 config.task_interval=任务周期 config.deliver_timeout=推送超时 +config.skip_tls_verify=忽略 TLS 验证 config.mailer_config=邮件配置 config.mailer_enabled=启用服务 config.mailer_name=发送者名称 diff --git a/conf/locale/locale_zh-HK.ini b/conf/locale/locale_zh-HK.ini index 0c9ba1909..a9b51a5b0 100755 --- a/conf/locale/locale_zh-HK.ini +++ b/conf/locale/locale_zh-HK.ini @@ -647,6 +647,7 @@ config.reset_password_code_lives=重置密碼連結有效期 config.webhook_config=Web 鉤子配置 config.task_interval=任務周期 config.deliver_timeout=推送超時 +config.skip_tls_verify=Skip TLS Verify config.mailer_config=郵件配置 config.mailer_enabled=啟用服務 config.mailer_name=發送者名稱 From a38e4a0b027f7be1f5523dc8e729f6f8300a8095 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Fri, 13 Feb 2015 16:48:23 -0500 Subject: [PATCH 03/30] routers/install.go: able to keep previous custom settings for 2nd time install - .gopmfile: update all commits --- .gopmfile | 41 ++++++++++++++++++++--------------------- routers/install.go | 6 ++++++ 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/.gopmfile b/.gopmfile index d09e632bd..e28fe0d3c 100644 --- a/.gopmfile +++ b/.gopmfile @@ -2,35 +2,34 @@ path = github.com/gogits/gogs [deps] -github.com/beego/memcache = commit:2aea774416 -github.com/bradfitz/gomemcache = +github.com/bradfitz/gomemcache = commit:72a68649ba github.com/Unknwon/cae = commit:2e70a1351b -github.com/Unknwon/com = commit:d9bcf409c8 +github.com/Unknwon/com = commit:188d690b1a github.com/Unknwon/i18n = commit:1e88666229 -github.com/Unknwon/macaron = -github.com/codegangsta/cli = commit:a14c5b47c7 -github.com/go-sql-driver/mysql = commit:04cf947760 -github.com/go-xorm/core = commit:e7882d8b00 -github.com/go-xorm/xorm = commit:dcc529b68a +github.com/Unknwon/macaron = commit:e089393c3f +github.com/codegangsta/cli = commit:6086d7927e +github.com/go-sql-driver/mysql = commit:27633f0519 +github.com/go-xorm/core = commit:16cb27928f +github.com/go-xorm/xorm = commit:f2d3be988e github.com/gogits/chardet = commit:2404f77725 github.com/gogits/go-gogs-client = commit:92e76d616a -github.com/lib/pq = commit:3e3efe51a0 -github.com/macaron-contrib/binding = commit:0fbe4b9707 -github.com/macaron-contrib/cache = -github.com/macaron-contrib/captcha = commit:3567dc48b8 -github.com/macaron-contrib/csrf = commit:3ea14e7ee7 -github.com/macaron-contrib/i18n = commit:0ee0539c84 +github.com/lib/pq = commit:835d5eb08d +github.com/macaron-contrib/binding = commit:dc739fabc3 +github.com/macaron-contrib/cache = commit:b68f6b448f +github.com/macaron-contrib/captcha = commit:066c50c7eb +github.com/macaron-contrib/csrf = commit:98ddf5a710 +github.com/macaron-contrib/i18n = commit:eeebd44f64 github.com/macaron-contrib/oauth2 = commit:8f394c3629 -github.com/macaron-contrib/session = -github.com/macaron-contrib/toolbox = commit:57127bcc89 -github.com/mattn/go-sqlite3 = commit:a80c27ba33 -github.com/microcosm-cc/bluemonday = +github.com/macaron-contrib/session = commit:8e8d938b27 +github.com/macaron-contrib/toolbox = commit:acbfe36e16 +github.com/mattn/go-sqlite3 = commit:25d045f12a +github.com/microcosm-cc/bluemonday = commit:fcd0f5074e github.com/nfnt/resize = commit:8f44931448 -github.com/russross/blackfriday = commit:05b8cefd6a -github.com/shurcooL/go = commit:48293cbc7a +github.com/russross/blackfriday = commit:77efab57b2 +github.com/shurcooL/go = commit:329f57438c golang.org/x/net = golang.org/x/text = -gopkg.in/ini.v1 = commit:28ad8c408b +gopkg.in/ini.v1 = commit:4febc4104c gopkg.in/redis.v2 = commit:e617904962 [res] diff --git a/routers/install.go b/routers/install.go index a3583a1a9..a7828e351 100644 --- a/routers/install.go +++ b/routers/install.go @@ -189,6 +189,12 @@ func InstallPost(ctx *middleware.Context, form auth.InstallForm) { // Save settings. cfg := ini.Empty() + if com.IsFile(setting.CustomConf) { + // Keeps custom settings if there is already something. + if err := cfg.Append(setting.CustomConf); err != nil { + log.Error(4, "Fail to load custom conf '%s': %v", setting.CustomConf, err) + } + } cfg.Section("database").Key("DB_TYPE").SetValue(models.DbCfg.Type) cfg.Section("database").Key("HOST").SetValue(models.DbCfg.Host) cfg.Section("database").Key("NAME").SetValue(models.DbCfg.Name) From 8c1986181dad8cb3e3205dc976f8077e187c664c Mon Sep 17 00:00:00 2001 From: Benjamin Pollack Date: Sat, 14 Feb 2015 15:31:07 -0500 Subject: [PATCH 04/30] Fix a bunch of small typos and formatting quirks --- CONTRIBUTING.md | 20 ++++++++++---------- README.md | 30 +++++++++++++++--------------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d3619018a..fc21ee038 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,20 +2,20 @@ > This guidelines sheet is forked from [CONTRIBUTING.md](https://github.com/drone/drone/blob/master/CONTRIBUTING.md). -Gogs is not perfect and it has bugs, or incomplete features for rare cases. You're welcome to tell us or contribute some code. This document describes details about how can you contribute to Gogs project. +Gogs is not perfect, and it has bugs or incomplete features in rare cases. You're welcome to tell us, or to contribute some code. This document describes details about how can you contribute to Gogs project. ## Contribution guidelines Depends on the situation, you will: -- Find bug, create an issue -- Need more functionality, make a feature request -- Want to contribute code, open a pull request -- Run into issue, need help +- Find a bug and create an issue +- Need more functionality and make a feature request +- Want to contribute code and open a pull request +- Run into issue and need help ### Bug Report -If you find or consider something is a bug, please create a issue on [GitHub](https://github.com/gogits/gogs/issues). To reduce unnecessary time wasting of interacting and waiting with team members, please include following information in the first place with a comfortable form for you: +If you find something you consider a bug, please create a issue on [GitHub](https://github.com/gogits/gogs/issues). To avoid wasting time and reduce back-and-forth communication with team members, please include at least the following information in a form comfortable for you: - Bug Description - Gogs Version @@ -28,7 +28,7 @@ Please take a moment to check that an issue on [GitHub](https://github.com/gogit #### Bug Report Example -Gogs crashed when create repository with license, using v0.5.13.0207, SQLite3, Git 1.9.0, Ubuntu 12.04. +Gogs crashed when creating a repository with a license, using v0.5.13.0207, SQLite3, Git 1.9.0, Ubuntu 12.04. Error log: @@ -38,11 +38,11 @@ Error log: ### Feature Request -There is no standard form of making a feature request, just try to describe the feature as clear as possible because team members may not have experience with the functionality you're talking about. +There is no standard form of making a feature request. Just try to describe the feature as clearly as possible, because team members may not have experience with the functionality you're talking about. ### Pull Request -Pull requests are always welcome, but note that **ALL PULL REQUESTS MUST SEND TO `DEV` BRANCH**. +Pull requests are always welcome, but note that **ALL PULL REQUESTS MUST APPLY TO THE `DEV` BRANCH**. We are always thrilled to receive pull requests, and do our best to process them as fast as possible. Not sure if that typo is worth a pull request? Do it! We will appreciate it. @@ -52,7 +52,7 @@ We're trying very hard to keep Gogs lean and focused. We don't want it to do eve ### Ask For Help -Before open any new issue, please check your problem on [Troubleshooting](http://gogs.io/docs/intro/troubleshooting.md) and [FAQs](http://gogs.io/docs/intro/faqs.html) pages. +Before opening a new issue, please check to make sure your problem isn't already addressed on the [Troubleshooting](http://gogs.io/docs/intro/troubleshooting.md) and [FAQs](http://gogs.io/docs/intro/faqs.html) pages. ## Things To Notice diff --git a/README.md b/README.md index a601bb773..150aa64de 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Gogs - Go Git Service [![Build Status](https://travis-ci.org/gogits/gogs.svg?bra [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gogits/gogs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -Gogs(Go Git Service) is a painless self-hosted Git Service written in Go. +Gogs (Go Git Service) is a painless self-hosted Git service written in Go. ![Demo](http://gogs.qiniudn.com/gogs_demo.gif) @@ -12,9 +12,9 @@ Gogs(Go Git Service) is a painless self-hosted Git Service written in Go. ### NOTICES - Due to testing purpose, data of [try.gogs.io](https://try.gogs.io) has been reset in **Jan 28, 2015** and will reset multiple times after. Please do **NOT** put your important data on the site. -- Demo site [try.gogs.io](https://try.gogs.io) is running under `dev` branch. +- The demo site [try.gogs.io](https://try.gogs.io) is running under `dev` branch. - You **MUST** read [CONTRIBUTING.md](CONTRIBUTING.md) before you start filing a issue or making a Pull Request. -- If you think there are vulnerabilities in the project, please talk private to **u@gogs.io**, thanks! +- If you think there are vulnerabilities in the project, please talk privately to **u@gogs.io**. Thanks! #### Other language version @@ -22,15 +22,15 @@ Gogs(Go Git Service) is a painless self-hosted Git Service written in Go. ## Purpose -The goal of this project is to make the easiest, fastest and most painless way to set up a self-hosted Git service. With Go, this can be done in independent binary distribution across **ALL platforms** that Go supports, including Linux, Mac OS X, and Windows. +The goal of this project is to make the easiest, fastest, and most painless way to set up a self-hosted Git service. With Go, this can be done via an independent binary distribution across **ALL platforms** that Go supports, including Linux, Mac OS X, and Windows. ## Overview -- Please see [Documentation](http://gogs.io/docs/intro/) for project design, known issues, and change log. -- See [Trello Board](https://trello.com/b/uxAoeLUl/gogs-go-git-service) to follow the develop team. -- Try it before anything? Do it [online](https://try.gogs.io/unknwon/gogs) or go down to **Installation -> Install from binary** section! -- Having troubles? Get help from [Troubleshooting](http://gogs.io/docs/intro/troubleshooting.md). -- Want to help on localization? Check out [Crowdin](https://crowdin.com/project/gogs)! +- Please see the [Documentation](http://gogs.io/docs/intro/) for project design, known issues, and change log. +- See the [Trello Board](https://trello.com/b/uxAoeLUl/gogs-go-git-service) to follow the develop team. +- Want to try it before doing anything else? Do it [online](https://try.gogs.io/unknwon/gogs) or go down to the **Installation -> Install from binary** section! +- Having trouble? Get help with [Troubleshooting](http://gogs.io/docs/intro/troubleshooting.md). +- Want to help with localization? Check out [Crowdin](https://crowdin.com/project/gogs)! ## Features @@ -46,22 +46,22 @@ The goal of this project is to make the easiest, fastest and most painless way t - Repository Git hooks - Add/remove repository collaborators - Gravatar and cache support -- Mail service(register, issue) +- Mail service (register, issue) - Administration panel - Slack webhook integration - Drone CI integration - Supports MySQL, PostgreSQL and SQLite3 -- Social account login(GitHub, Google, QQ, Weibo) -- Multi-language support([10 languages](https://crowdin.com/project/gogs)) +- Social account login (GitHub, Google, QQ, Weibo) +- Multi-language support ([10 languages](https://crowdin.com/project/gogs)) ## System Requirements -- A cheap Raspberry Pi is powerful enough to match the minimal requirement. -- 4 CPU Cores and 1GB RAM would be the baseline for teamwork. +- A cheap Raspberry Pi is powerful enough for basic functionality. +- At least 4 CPU cores and 1GB RAM would be the baseline for teamwork. ## Installation -Make sure you install [Prerequirements](http://gogs.io/docs/installation/) first. +Make sure you install the [prerequisites](http://gogs.io/docs/installation/) first. There are 5 ways to install Gogs: From 685ed1f8075c0fedc2cfaf0f8c43f9439132e1da Mon Sep 17 00:00:00 2001 From: Unknwon Date: Sat, 14 Feb 2015 17:01:33 -0500 Subject: [PATCH 05/30] models: fix XORM API break cmd/web.go: check version after load config --- cmd/web.go | 3 +-- gogs.go | 2 +- models/models.go | 2 +- templates/.VERSION | 2 +- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/cmd/web.go b/cmd/web.go index 3284acb9d..4b06a882c 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -166,12 +166,11 @@ func newMacaron() *macaron.Macaron { } func runWeb(ctx *cli.Context) { - checkVersion() - if ctx.IsSet("config") { setting.CustomConf = ctx.String("config") } routers.GlobalInit() + checkVersion() m := newMacaron() diff --git a/gogs.go b/gogs.go index 76c6c71fc..34790b725 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.5.13.0212 Beta" +const APP_VER = "0.5.13.0214 Beta" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/models.go b/models/models.go index 35e803834..486aceac2 100644 --- a/models/models.go +++ b/models/models.go @@ -121,7 +121,7 @@ func SetEngine() (err error) { if err != nil { return fmt.Errorf("models.init(fail to create xorm.log): %v", err) } - x.Logger = xorm.NewSimpleLogger(f) + x.SetLogger(xorm.NewSimpleLogger(f)) x.ShowSQL = true x.ShowInfo = true diff --git a/templates/.VERSION b/templates/.VERSION index 6d13155b0..0c9421a4d 100644 --- a/templates/.VERSION +++ b/templates/.VERSION @@ -1 +1 @@ -0.5.13.0212 Beta \ No newline at end of file +0.5.13.0214 Beta \ No newline at end of file From f625665d8d72fdc4d2ce28a88aaaf01eaf5c2370 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Sat, 14 Feb 2015 17:49:33 -0500 Subject: [PATCH 06/30] modules/setting: add abs path check before add workdir prefix --- modules/setting/setting.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 6664c4190..52dca3f04 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -240,7 +240,10 @@ func NewConfigContext() { ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER") sec = Cfg.Section("attachment") - AttachmentPath = path.Join(workDir, sec.Key("PATH").MustString("data/attachments")) + AttachmentPath = sec.Key("PATH").MustString("data/attachments") + if !filepath.IsAbs(AttachmentPath) { + AttachmentPath = path.Join(workDir, AttachmentPath) + } AttachmentAllowedTypes = sec.Key("ALLOWED_TYPES").MustString("image/jpeg|image/png") AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(32) AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(10) @@ -297,7 +300,10 @@ func NewConfigContext() { sec = Cfg.Section("picture") PictureService = sec.Key("SERVICE").In("server", []string{"server"}) - AvatarUploadPath = path.Join(workDir, sec.Key("AVATAR_UPLOAD_PATH").MustString("data/avatars")) + AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString("data/avatars") + if !filepath.IsAbs(AvatarUploadPath) { + AvatarUploadPath = path.Join(workDir, AvatarUploadPath) + } os.MkdirAll(AvatarUploadPath, os.ModePerm) switch sec.Key("GRAVATAR_SOURCE").MustString("gravatar") { case "duoshuo": From d85366930c94145c8f1119ff0b6bb95d77c5200e Mon Sep 17 00:00:00 2001 From: Unknwon Date: Mon, 16 Feb 2015 02:51:39 -0500 Subject: [PATCH 07/30] update travis.yml --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 85e5f396e..4149e1731 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,4 +12,5 @@ script: go build -v notifications: email: - - u@gogs.io \ No newline at end of file + - u@gogs.io + slack: gophercn:o5pSanyTeNhnfYc3QnG0X7Wx \ No newline at end of file From f9454cc32c94780eb4c49753fc0ccd9b60b1deb7 Mon Sep 17 00:00:00 2001 From: Peter Smit Date: Mon, 16 Feb 2015 12:00:06 +0200 Subject: [PATCH 08/30] Make sure that a mirror can't be written to by http or ssh --- cmd/serve.go | 5 +++++ routers/repo/http.go | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/cmd/serve.go b/cmd/serve.go index e8e5c186c..9e34b95c5 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -164,6 +164,11 @@ func runServ(c *cli.Context) { println("You have no right to write this repository") log.GitLogger.Fatal(2, "User %s has no right to write repository %s", user.Name, repoPath) } + + if repo.IsMirror { + println("You can't write to a mirror repository") + log.GitLogger.Fatal(2, "User %s tried to write to a mirror repository %s", user.Name, repoPath) + } case isRead: if !repo.IsPrivate { break diff --git a/routers/repo/http.go b/routers/repo/http.go index 034b5a7b5..d47d73ef0 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -158,6 +158,11 @@ func Http(ctx *middleware.Context) { return } } + + if !isPull && repo.IsMirror { + ctx.Handle(401, "can't push to mirror", nil) + return + } } } From ed89b39984a9191380263eaf357c3a9c71770674 Mon Sep 17 00:00:00 2001 From: Peter Smit Date: Mon, 16 Feb 2015 12:51:56 +0200 Subject: [PATCH 09/30] Updating context and fixing permission issues The boolean flags in the repo context have been replaced with mode and two methods Also, the permissions have been brought more in line with https://help.github.com/articles/permission-levels-for-an-organization-repository/ , Admin Team members are able to change settings of their repositories. --- cmd/web.go | 4 +-- modules/middleware/context.go | 55 ++++++++++++++++++++--------------- modules/middleware/repo.go | 47 +++++++++++------------------- routers/api/v1/repo_file.go | 2 +- routers/repo/issue.go | 14 ++++----- routers/repo/release.go | 10 +++---- routers/repo/repo.go | 2 +- templates/repo/header.tmpl | 2 +- templates/repo/sidebar.tmpl | 2 +- templates/repo/toolbar.tmpl | 2 +- 10 files changed, 68 insertions(+), 72 deletions(-) diff --git a/cmd/web.go b/cmd/web.go index 3284acb9d..8b3b03c45 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -319,7 +319,7 @@ func runWeb(ctx *cli.Context) { m.Get("/template/*", dev.TemplatePreview) } - reqTrueOwner := middleware.RequireTrueOwner() + reqAdmin := middleware.RequireAdmin() // Organization. m.Group("/org", func() { @@ -394,7 +394,7 @@ func runWeb(ctx *cli.Context) { m.Post("/:name", repo.GitHooksEditPost) }, middleware.GitHookService()) }) - }, reqSignIn, middleware.RepoAssignment(true), reqTrueOwner) + }, reqSignIn, middleware.RepoAssignment(true), reqAdmin) m.Group("/:username/:reponame", func() { m.Get("/action/:action", repo.Action) diff --git a/modules/middleware/context.go b/modules/middleware/context.go index 28be3a302..a26610969 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -38,29 +38,7 @@ type Context struct { IsSigned bool IsBasicAuth bool - Repo struct { - IsOwner bool - IsTrueOwner bool - IsWatching bool - IsBranch bool - IsTag bool - IsCommit bool - IsAdmin bool // Current user is admin level. - HasAccess bool - Repository *models.Repository - Owner *models.User - Commit *git.Commit - Tag *git.Tag - GitRepo *git.Repository - BranchName string - TagName string - TreeName string - CommitId string - RepoLink string - CloneLink models.CloneLink - CommitsCount int - Mirror *models.Mirror - } + Repo RepoContext Org struct { IsOwner bool @@ -73,6 +51,37 @@ type Context struct { } } +type RepoContext struct { + AccessMode models.AccessMode + IsWatching bool + IsBranch bool + IsTag bool + IsCommit bool + Repository *models.Repository + Owner *models.User + Commit *git.Commit + Tag *git.Tag + GitRepo *git.Repository + BranchName string + TagName string + TreeName string + CommitId string + RepoLink string + CloneLink models.CloneLink + CommitsCount int + Mirror *models.Mirror +} + +// Return if the current user has write access for this repository +func (r RepoContext) IsOwner() bool { + return r.AccessMode >= models.ACCESS_MODE_WRITE +} + +// Return if the current user has read access for this repository +func (r RepoContext) HasAccess() bool { + return r.AccessMode >= models.ACCESS_MODE_READ +} + // HasError returns true if error occurs in form validation. func (ctx *Context) HasApiError() bool { hasErr, ok := ctx.Data["HasError"] diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index bd298819d..5c863dc01 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -58,24 +58,19 @@ func ApiRepoAssignment() macaron.Handler { return } - if ctx.IsSigned { - mode, err := models.AccessLevel(ctx.User, repo) - if err != nil { - ctx.JSON(500, &base.ApiJsonErr{"AccessLevel: " + err.Error(), base.DOC_URL}) - return - } - - ctx.Repo.IsOwner = mode >= models.ACCESS_MODE_WRITE - ctx.Repo.IsAdmin = mode >= models.ACCESS_MODE_READ - ctx.Repo.IsTrueOwner = mode >= models.ACCESS_MODE_OWNER + mode, err := models.AccessLevel(ctx.User, repo) + if err != nil { + ctx.JSON(500, &base.ApiJsonErr{"AccessLevel: " + err.Error(), base.DOC_URL}) + return } + ctx.Repo.AccessMode = mode + // Check access. - if repo.IsPrivate && !ctx.Repo.IsOwner { + if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE { ctx.Error(404) return } - ctx.Repo.HasAccess = true ctx.Repo.Repository = repo } @@ -239,26 +234,18 @@ func RepoAssignment(redirect bool, args ...bool) macaron.Handler { return } - if ctx.IsSigned { - mode, err := models.AccessLevel(ctx.User, repo) - if err != nil { - ctx.Handle(500, "AccessLevel", err) - return - } - ctx.Repo.IsOwner = mode >= models.ACCESS_MODE_WRITE - ctx.Repo.IsAdmin = mode >= models.ACCESS_MODE_READ - ctx.Repo.IsTrueOwner = mode >= models.ACCESS_MODE_OWNER - if !ctx.Repo.IsTrueOwner && ctx.Repo.Owner.IsOrganization() { - ctx.Repo.IsTrueOwner = ctx.Repo.Owner.IsOwnedBy(ctx.User.Id) - } + mode, err := models.AccessLevel(ctx.User, repo) + if err != nil { + ctx.Handle(500, "AccessLevel", err) + return } + ctx.Repo.AccessMode = mode // Check access. - if repo.IsPrivate && !ctx.Repo.IsOwner { + if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE { ctx.Handle(404, "no access right", err) return } - ctx.Repo.HasAccess = true ctx.Data["HasAccess"] = true @@ -306,8 +293,8 @@ func RepoAssignment(redirect bool, args ...bool) macaron.Handler { ctx.Data["Title"] = u.Name + "/" + repo.Name ctx.Data["Repository"] = repo ctx.Data["Owner"] = ctx.Repo.Repository.Owner - ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner - ctx.Data["IsRepositoryTrueOwner"] = ctx.Repo.IsTrueOwner + ctx.Data["IsRepositoryOwner"] = ctx.Repo.AccessMode >= models.ACCESS_MODE_WRITE + ctx.Data["IsRepositoryAdmin"] = ctx.Repo.AccessMode >= models.ACCESS_MODE_ADMIN ctx.Data["DisableSSH"] = setting.DisableSSH ctx.Repo.CloneLink, err = repo.CloneLink() @@ -362,9 +349,9 @@ func RepoAssignment(redirect bool, args ...bool) macaron.Handler { } } -func RequireTrueOwner() macaron.Handler { +func RequireAdmin() macaron.Handler { return func(ctx *Context) { - if !ctx.Repo.IsTrueOwner && !ctx.Repo.IsAdmin { + if ctx.Repo.AccessMode < models.ACCESS_MODE_ADMIN { if !ctx.IsSigned { ctx.SetCookie("redirect_to", "/"+url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl) ctx.Redirect(setting.AppSubUrl + "/user/login") diff --git a/routers/api/v1/repo_file.go b/routers/api/v1/repo_file.go index a049904f9..73f97b2ca 100644 --- a/routers/api/v1/repo_file.go +++ b/routers/api/v1/repo_file.go @@ -12,7 +12,7 @@ import ( ) func GetRepoRawFile(ctx *middleware.Context) { - if ctx.Repo.Repository.IsPrivate && !ctx.Repo.HasAccess { + if !ctx.Repo.HasAccess() { ctx.Error(404) return } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index bf39d9aba..40e933897 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -230,7 +230,7 @@ func CreateIssuePost(ctx *middleware.Context, form auth.CreateIssueForm) { } // Only collaborators can assign. - if !ctx.Repo.IsOwner { + if !ctx.Repo.IsOwner() { form.AssigneeId = 0 } issue := &models.Issue{ @@ -434,7 +434,7 @@ func ViewIssue(ctx *middleware.Context) { ctx.Data["Title"] = issue.Name ctx.Data["Issue"] = issue ctx.Data["Comments"] = comments - ctx.Data["IsIssueOwner"] = ctx.Repo.IsOwner || (ctx.IsSigned && issue.PosterId == ctx.User.Id) + ctx.Data["IsIssueOwner"] = ctx.Repo.IsOwner() || (ctx.IsSigned && issue.PosterId == ctx.User.Id) ctx.Data["IsRepoToolbarIssues"] = true ctx.Data["IsRepoToolbarIssuesList"] = false ctx.HTML(200, ISSUE_VIEW) @@ -457,7 +457,7 @@ func UpdateIssue(ctx *middleware.Context, form auth.CreateIssueForm) { return } - if ctx.User.Id != issue.PosterId && !ctx.Repo.IsOwner { + if ctx.User.Id != issue.PosterId && !ctx.Repo.IsOwner() { ctx.Error(403) return } @@ -484,7 +484,7 @@ func UpdateIssue(ctx *middleware.Context, form auth.CreateIssueForm) { } func UpdateIssueLabel(ctx *middleware.Context) { - if !ctx.Repo.IsOwner { + if !ctx.Repo.IsOwner() { ctx.Error(403) return } @@ -560,7 +560,7 @@ func UpdateIssueLabel(ctx *middleware.Context) { } func UpdateIssueMilestone(ctx *middleware.Context) { - if !ctx.Repo.IsOwner { + if !ctx.Repo.IsOwner() { ctx.Error(403) return } @@ -606,7 +606,7 @@ func UpdateIssueMilestone(ctx *middleware.Context) { } func UpdateAssignee(ctx *middleware.Context) { - if !ctx.Repo.IsOwner { + if !ctx.Repo.IsOwner() { ctx.Error(403) return } @@ -752,7 +752,7 @@ func Comment(ctx *middleware.Context) { // Check if issue owner changes the status of issue. var newStatus string - if ctx.Repo.IsOwner || issue.PosterId == ctx.User.Id { + if ctx.Repo.IsOwner() || issue.PosterId == ctx.User.Id { newStatus = ctx.Query("change_status") } if len(newStatus) > 0 { diff --git a/routers/repo/release.go b/routers/repo/release.go index 591810cc5..52d78b196 100644 --- a/routers/repo/release.go +++ b/routers/repo/release.go @@ -41,7 +41,7 @@ func Releases(ctx *middleware.Context) { tags := make([]*models.Release, len(rawTags)) for i, rawTag := range rawTags { for j, rel := range rels { - if rel == nil || (rel.IsDraft && !ctx.Repo.IsOwner) { + if rel == nil || (rel.IsDraft && !ctx.Repo.IsOwner()) { continue } if rel.TagName == rawTag { @@ -140,7 +140,7 @@ func Releases(ctx *middleware.Context) { } func NewRelease(ctx *middleware.Context) { - if !ctx.Repo.IsOwner { + if !ctx.Repo.IsOwner() { ctx.Handle(403, "release.ReleasesNew", nil) return } @@ -153,7 +153,7 @@ func NewRelease(ctx *middleware.Context) { } func NewReleasePost(ctx *middleware.Context, form auth.NewReleaseForm) { - if !ctx.Repo.IsOwner { + if !ctx.Repo.IsOwner() { ctx.Handle(403, "release.ReleasesNew", nil) return } @@ -211,7 +211,7 @@ func NewReleasePost(ctx *middleware.Context, form auth.NewReleaseForm) { } func EditRelease(ctx *middleware.Context) { - if !ctx.Repo.IsOwner { + if !ctx.Repo.IsOwner() { ctx.Handle(403, "release.ReleasesEdit", nil) return } @@ -234,7 +234,7 @@ func EditRelease(ctx *middleware.Context) { } func EditReleasePost(ctx *middleware.Context, form auth.EditReleaseForm) { - if !ctx.Repo.IsOwner { + if !ctx.Repo.IsOwner() { ctx.Handle(403, "release.EditReleasePost", nil) return } diff --git a/routers/repo/repo.go b/routers/repo/repo.go index 48f7b09bc..005372003 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -343,7 +343,7 @@ func Action(ctx *middleware.Context) { case "unstar": err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.Id, false) case "desc": - if !ctx.Repo.IsOwner { + if !ctx.Repo.IsOwner() { ctx.Error(404) return } diff --git a/templates/repo/header.tmpl b/templates/repo/header.tmpl index a0b927be6..21f9cea88 100644 --- a/templates/repo/header.tmpl +++ b/templates/repo/header.tmpl @@ -49,7 +49,7 @@
  • - +
  • -->{{end}}{{if .IsRepositoryTrueOwner}} + -->{{end}}{{if .IsRepositoryAdmin}}
  • Settings
  • {{end}} From b6519f78c704bf70b48e63f960ef88d430e07b3b Mon Sep 17 00:00:00 2001 From: Peter Smit Date: Mon, 16 Feb 2015 13:25:55 +0200 Subject: [PATCH 10/30] Remove collaborators when removing and transferring repository --- models/repo.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/models/repo.go b/models/repo.go index fd00823a2..388bcd0e5 100644 --- a/models/repo.go +++ b/models/repo.go @@ -670,6 +670,19 @@ func TransferOwnership(u *User, newOwner string, repo *Repository) error { return err } + // Remove redundant collaborators + collaborators, err := repo.GetCollaborators() + if err != nil { + return err + } + for _, c := range collaborators { + if c.Id == newUser.Id || newUser.IsOrgMember(c.Id) { + if _, err = sess.Delete(&Collaboration{RepoID: repo.Id, UserID: c.Id}); err != nil { + return err + } + } + } + // Update user repository number. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", newUser.Id); err != nil { return err @@ -778,6 +791,8 @@ func DeleteRepository(uid, repoId int64, userName string) error { return err } else if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil { return err + } else if _, err = sess.Delete(&Collaboration{RepoID: repoId}); err != nil { + return err } // Delete comments. From 7759b9ee6efb069a1f846b43bd6bc981f998e55a Mon Sep 17 00:00:00 2001 From: Peter Smit Date: Mon, 16 Feb 2015 14:44:27 +0200 Subject: [PATCH 11/30] Remove the "PHP" style formatting function The "PHP" formatting function doesn't add anything, except an undocumented date format. All usages in the templates have been replaced with DateFmtShort and DateFmtLong for convenience. --- modules/base/template.go | 9 ++- modules/base/tool.go | 67 ++--------------------- templates/admin/auth/list.tmpl | 4 +- templates/admin/org/list.tmpl | 2 +- templates/admin/repo/list.tmpl | 2 +- templates/admin/user/list.tmpl | 2 +- templates/user/profile.tmpl | 2 +- templates/user/settings/applications.tmpl | 2 +- templates/user/settings/social.tmpl | 2 +- templates/user/settings/sshkeys.tmpl | 2 +- 10 files changed, 22 insertions(+), 72 deletions(-) diff --git a/modules/base/template.go b/modules/base/template.go index f3fa13857..0fd519e6c 100644 --- a/modules/base/template.go +++ b/modules/base/template.go @@ -126,8 +126,13 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{ return a + b }, "ActionIcon": ActionIcon, - "DateFormat": DateFormat, - "List": List, + "DateFmtLong": func(t time.Time) string { + return t.Format(time.RFC1123Z) + }, + "DateFmtShort": func(t time.Time) string { + return t.Format("Jan 02, 2006") + }, + "List": List, "Mail2Domain": func(mail string) string { if !strings.Contains(mail, "@") { return "try.gogs.io" diff --git a/modules/base/tool.go b/modules/base/tool.go index 5043364ce..55e6dffd9 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -126,7 +126,7 @@ func VerifyTimeLimitCode(data string, minutes int, code string) bool { retCode := CreateTimeLimitCode(data, minutes, start) if retCode == code && minutes > 0 { // check time is expired or not - before, _ := DateParse(start, "YmdHi") + before, _ := time.ParseInLocation("200601021504", start, time.Local) now := time.Now() if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() { return true @@ -141,7 +141,7 @@ const TimeLimitCodeLength = 12 + 6 + 40 // create a time limit code // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string { - format := "YmdHi" + format := "200601021504" var start, end time.Time var startStr, endStr string @@ -149,16 +149,16 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string if startInf == nil { // Use now time create code start = time.Now() - startStr = DateFormat(start, format) + startStr = start.Format(format) } else { // use start string create code startStr = startInf.(string) - start, _ = DateParse(startStr, format) - startStr = DateFormat(start, format) + start, _ = time.ParseInLocation(format, startStr, time.Local) + startStr = start.Format(format) } end = start.Add(time.Minute * time.Duration(minutes)) - endStr = DateFormat(end, format) + endStr = end.Format(format) // create sha1 encode string sh := sha1.New() @@ -420,58 +420,3 @@ func Subtract(left interface{}, right interface{}) interface{} { return fleft + float64(rleft) - (fright + float64(rright)) } } - -// DateFormat pattern rules. -var datePatterns = []string{ - // year - "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003 - "y", "06", //A two digit representation of a year Examples: 99 or 03 - - // month - "m", "01", // Numeric representation of a month, with leading zeros 01 through 12 - "n", "1", // Numeric representation of a month, without leading zeros 1 through 12 - "M", "Jan", // A short textual representation of a month, three letters Jan through Dec - "F", "January", // A full textual representation of a month, such as January or March January through December - - // day - "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31 - "j", "2", // Day of the month without leading zeros 1 to 31 - - // week - "D", "Mon", // A textual representation of a day, three letters Mon through Sun - "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday - - // time - "g", "3", // 12-hour format of an hour without leading zeros 1 through 12 - "G", "15", // 24-hour format of an hour without leading zeros 0 through 23 - "h", "03", // 12-hour format of an hour with leading zeros 01 through 12 - "H", "15", // 24-hour format of an hour with leading zeros 00 through 23 - - "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm - "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM - - "i", "04", // Minutes with leading zeros 00 to 59 - "s", "05", // Seconds, with leading zeros 00 through 59 - - // time zone - "T", "MST", - "P", "-07:00", - "O", "-0700", - - // RFC 2822 - "r", time.RFC1123Z, -} - -// Parse Date use PHP time format. -func DateParse(dateString, format string) (time.Time, error) { - replacer := strings.NewReplacer(datePatterns...) - format = replacer.Replace(format) - return time.ParseInLocation(format, dateString, time.Local) -} - -// Date takes a PHP like date func to Go's time format. -func DateFormat(t time.Time, format string) string { - replacer := strings.NewReplacer(datePatterns...) - format = replacer.Replace(format) - return t.Format(format) -} diff --git a/templates/admin/auth/list.tmpl b/templates/admin/auth/list.tmpl index aba516b8e..ec701a8f8 100644 --- a/templates/admin/auth/list.tmpl +++ b/templates/admin/auth/list.tmpl @@ -34,8 +34,8 @@ {{.Name}} {{.TypeString}} - {{DateFormat .Updated "M d, Y"}} - {{DateFormat .Created "M d, Y"}} + {{DateFmtShort .Updated}} + {{DateFmtShort .Created}} {{end}} diff --git a/templates/admin/org/list.tmpl b/templates/admin/org/list.tmpl index b522dc08a..ce5083a0a 100644 --- a/templates/admin/org/list.tmpl +++ b/templates/admin/org/list.tmpl @@ -35,7 +35,7 @@ {{.NumTeams}} {{.NumMembers}} {{.NumRepos}} - {{DateFormat .Created "M d, Y"}} + {{DateFmtShort .Created}} {{end}} diff --git a/templates/admin/repo/list.tmpl b/templates/admin/repo/list.tmpl index 88e16a433..981e2ef72 100644 --- a/templates/admin/repo/list.tmpl +++ b/templates/admin/repo/list.tmpl @@ -37,7 +37,7 @@ {{.NumWatches}} {{.NumStars}} {{.NumIssues}} - {{DateFormat .Created "M d, Y"}} + {{DateFmtShort .Created}} {{end}} diff --git a/templates/admin/user/list.tmpl b/templates/admin/user/list.tmpl index d42d52910..1dd5553eb 100644 --- a/templates/admin/user/list.tmpl +++ b/templates/admin/user/list.tmpl @@ -37,7 +37,7 @@ {{.NumRepos}} - {{DateFormat .Created "M d, Y"}} + {{DateFmtShort .Created }} {{end}} diff --git a/templates/user/profile.tmpl b/templates/user/profile.tmpl index 44c221238..a18a8b50d 100644 --- a/templates/user/profile.tmpl +++ b/templates/user/profile.tmpl @@ -28,7 +28,7 @@ {{if .Owner.Website}}
  •   {{.Owner.Website}}
  • {{end}} -
  •   {{.i18n.Tr "user.join_on"}} {{DateFormat .Owner.Created "M d, Y"}}
  • +
  •   {{.i18n.Tr "user.join_on"}} {{DateFmtShort .Owner.Created}}

    • diff --git a/templates/user/settings/applications.tmpl b/templates/user/settings/applications.tmpl index ce74ef776..2e766a3dc 100644 --- a/templates/user/settings/applications.tmpl +++ b/templates/user/settings/applications.tmpl @@ -22,7 +22,7 @@

      {{.Name}}

      -

      {{$.i18n.Tr "settings.add_on"}} {{DateFormat .Created "M d, Y"}}{{if .HasUsed}}{{$.i18n.Tr "settings.last_used"}} {{DateFormat .Updated "M d, Y"}}{{else}}{{$.i18n.Tr "settings.no_activity"}}{{end}}

      +

      {{$.i18n.Tr "settings.add_on"}} {{DateFmtShort .Created}}{{if .HasUsed}}{{$.i18n.Tr "settings.last_used"}} {{DateFmtShort .Updated}}{{else}}{{$.i18n.Tr "settings.no_activity"}}{{end}}

      diff --git a/templates/user/settings/social.tmpl b/templates/user/settings/social.tmpl index b47f883e5..f2a30da79 100644 --- a/templates/user/settings/social.tmpl +++ b/templates/user/settings/social.tmpl @@ -18,7 +18,7 @@

      {{Oauth2Name .Type}}

      {{.Identity}}

      -

      {{$.i18n.Tr "settings.add_on"}} {{DateFormat .Created "M d, Y"}}{{$.i18n.Tr "settings.last_used"}} {{DateFormat .Updated "M d, Y"}}

      +

      {{$.i18n.Tr "settings.add_on"}} {{DateFmtShort .Created}}{{$.i18n.Tr "settings.last_used"}} {{DateFmtShort .Updated}}

      {{$.i18n.Tr "settings.unbind"}} diff --git a/templates/user/settings/sshkeys.tmpl b/templates/user/settings/sshkeys.tmpl index 48a4d343a..42b76039e 100644 --- a/templates/user/settings/sshkeys.tmpl +++ b/templates/user/settings/sshkeys.tmpl @@ -23,7 +23,7 @@

      {{.Name}}

      {{.Fingerprint}}

      -

      {{$.i18n.Tr "settings.add_on"}} {{DateFormat .Created "M d, Y"}}{{if .HasUsed}}{{$.i18n.Tr "settings.last_used"}} {{DateFormat .Updated "M d, Y"}}{{else}}{{$.i18n.Tr "settings.no_activity"}}{{end}}

      +

      {{$.i18n.Tr "settings.add_on"}} {{DateFmtShort .Created}}{{if .HasUsed}}{{$.i18n.Tr "settings.last_used"}} {{DateFmtShort .Updated}}{{else}}{{$.i18n.Tr "settings.no_activity"}}{{end}}

      {{$.CsrfTokenHtml}} From e6fc58a74461bd67efb06fc2e5658265ede2edb5 Mon Sep 17 00:00:00 2001 From: Peter Smit Date: Tue, 17 Feb 2015 10:36:17 +0200 Subject: [PATCH 12/30] Remove GoGet option from repository and handle it with ?go-get=1 instead The normal go get protocol is to show the go-import meta tag when ?go-get=1 is appended to the url. This commit implements that behaviour and cleans the go-get option from the repository settings page. --- conf/locale/locale_en-US.ini | 2 -- models/repo.go | 1 - modules/auth/repo_form.go | 1 - modules/middleware/repo.go | 3 +-- routers/repo/setting.go | 3 +-- templates/base/head.tmpl | 2 +- templates/ng/base/head.tmpl | 2 +- templates/repo/settings/options.tmpl | 5 ----- 8 files changed, 4 insertions(+), 15 deletions(-) diff --git a/conf/locale/locale_en-US.ini b/conf/locale/locale_en-US.ini index 6b59be739..54b80abb5 100644 --- a/conf/locale/locale_en-US.ini +++ b/conf/locale/locale_en-US.ini @@ -281,8 +281,6 @@ init_readme = Initialize this repository with a README.md create_repo = Create Repository default_branch = Default Branch mirror_interval = Mirror Interval (hour) -goget_meta = Go-Get Meta -goget_meta_helper = This repository will be Go-Getable need_auth = Need Authorization migrate_type = Migration Type diff --git a/models/repo.go b/models/repo.go index cdb838a1f..179120a31 100644 --- a/models/repo.go +++ b/models/repo.go @@ -154,7 +154,6 @@ type Repository struct { IsPrivate bool IsBare bool - IsGoget bool IsMirror bool *Mirror `xorm:"-"` diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index 36e62f04f..c771dd59b 100644 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -52,7 +52,6 @@ type RepoSettingForm struct { Branch string `form:"branch"` Interval int `form:"interval"` Private bool `form:"private"` - GoGet bool `form:"goget"` } func (f *RepoSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index 1ab158dd6..67a9eda69 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -394,8 +394,7 @@ func RepoAssignment(redirect bool, args ...bool) macaron.Handler { } ctx.Data["CloneLink"] = ctx.Repo.CloneLink - if ctx.Repo.Repository.IsGoget { - ctx.Data["GoGetLink"] = fmt.Sprintf("%s%s/%s", setting.AppUrl, u.LowerName, repo.LowerName) + if ctx.Query("go-get") == "1" { ctx.Data["GoGetImport"] = fmt.Sprintf("%s/%s/%s", setting.Domain, u.LowerName, repo.LowerName) } diff --git a/routers/repo/setting.go b/routers/repo/setting.go index 33bf1eab2..8368513ad 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -8,9 +8,9 @@ import ( "encoding/json" "errors" "fmt" + "path" "strings" "time" - "path" "github.com/Unknwon/com" @@ -84,7 +84,6 @@ func SettingsPost(ctx *middleware.Context, form auth.RepoSettingForm) { ctx.Repo.Repository.Description = form.Description ctx.Repo.Repository.Website = form.Website ctx.Repo.Repository.IsPrivate = form.Private - ctx.Repo.Repository.IsGoget = form.GoGet if err := models.UpdateRepository(ctx.Repo.Repository); err != nil { ctx.Handle(404, "UpdateRepository", err) return diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index 7775933ca..cb3951ea2 100644 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -9,7 +9,7 @@ - {{if .Repository.IsGoget}}{{end}} + {{if .GoGetImport}}{{end}} {{if CdnMode}} diff --git a/templates/ng/base/head.tmpl b/templates/ng/base/head.tmpl index 40a7d28ff..f2a235bd4 100644 --- a/templates/ng/base/head.tmpl +++ b/templates/ng/base/head.tmpl @@ -7,7 +7,7 @@ - {{if .Repository.IsGoget}}{{end}} + {{if .GoGetImport}}{{end}} diff --git a/templates/repo/settings/options.tmpl b/templates/repo/settings/options.tmpl index 093e93755..41683f845 100644 --- a/templates/repo/settings/options.tmpl +++ b/templates/repo/settings/options.tmpl @@ -59,11 +59,6 @@ {{.i18n.Tr "repo.visiblity_helper" | Str2html}}
    -
    - - - {{.i18n.Tr "repo.goget_meta_helper" | Str2html}} -
    From 6e341e26b30090a335861da35b9cc09977b971a4 Mon Sep 17 00:00:00 2001 From: Stefan-Code Date: Wed, 18 Feb 2015 07:20:06 +0100 Subject: [PATCH 13/30] added less compile script --- scripts/less.sh | 5 +++++ 1 file changed, 5 insertions(+) create mode 100755 scripts/less.sh diff --git a/scripts/less.sh b/scripts/less.sh new file mode 100755 index 000000000..ff2f57360 --- /dev/null +++ b/scripts/less.sh @@ -0,0 +1,5 @@ +#!/bin/sh +echo "compiling LESS Files" +lessc ../public/ng/less/gogs.less ../public/ng/css/gogs.css +lessc ../public/ng/less/ui.less ../public/ng/css/ui.css +echo "done" From 1628ef4ba5120d338c0616e37153f9f9b2f8f236 Mon Sep 17 00:00:00 2001 From: Stefan-Code Date: Wed, 18 Feb 2015 08:22:13 +0100 Subject: [PATCH 14/30] changed repo-clone-url behaviour for bare repo --- public/ng/css/gogs.css | 4 +--- public/ng/less/gogs/repository.less | 4 +--- templates/repo/bare.tmpl | 4 ++-- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/public/ng/css/gogs.css b/public/ng/css/gogs.css index 9f6cf12f9..43931e94d 100644 --- a/public/ng/css/gogs.css +++ b/public/ng/css/gogs.css @@ -1066,9 +1066,6 @@ The register and sign-in page style #repo-header-download-drop .btn > i { margin-right: 6px; } -#repo-header-download-drop input { - cursor: default; -} #repo-header-download-drop button, #repo-header-download-drop input { font-size: 11px; @@ -1089,6 +1086,7 @@ The register and sign-in page style border-right: none; width: 190px; border-left: none; + cursor: default; } #repo-clone-help { clear: both; diff --git a/public/ng/less/gogs/repository.less b/public/ng/less/gogs/repository.less index d683d0334..63c25d06b 100644 --- a/public/ng/less/gogs/repository.less +++ b/public/ng/less/gogs/repository.less @@ -81,9 +81,6 @@ .btn>i { margin-right: 6px; } - input { - cursor: default; - } button, input { font-size: 11px; } @@ -104,6 +101,7 @@ border-right: none; width: 190px; border-left: none; + cursor: default; } #repo-clone-help { clear: both; diff --git a/templates/repo/bare.tmpl b/templates/repo/bare.tmpl index 2a1409a6e..c050b6238 100644 --- a/templates/repo/bare.tmpl +++ b/templates/repo/bare.tmpl @@ -23,7 +23,7 @@

    {{.i18n.Tr "repo.clone_this_repo"}}

    - +

    {{.i18n.Tr "repo.clone_helper" | Str2html}}


    @@ -50,4 +50,4 @@ git push -u origin master
    -{{template "ng/base/footer" .}} \ No newline at end of file +{{template "ng/base/footer" .}} From 563e8b4ea98e57adf3992dcaef76b86d29c13cec Mon Sep 17 00:00:00 2001 From: Alexey Makhov Date: Thu, 19 Feb 2015 00:52:22 +0300 Subject: [PATCH 15/30] gitlab-like hash naming --- modules/base/template.go | 5 +++++ public/ng/js/gogs.js | 20 ++++++++++---------- templates/repo/diff.tmpl | 6 +++--- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/modules/base/template.go b/modules/base/template.go index 0fd519e6c..cfcabb71a 100644 --- a/modules/base/template.go +++ b/modules/base/template.go @@ -41,6 +41,10 @@ func List(l *list.List) chan interface{} { return c } +func Sha1(str string) string { + return EncodeSha1(str) +} + func ShortSha(sha1 string) string { if len(sha1) == 40 { return sha1[:10] @@ -160,6 +164,7 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{ }, "DiffTypeToStr": DiffTypeToStr, "DiffLineTypeToStr": DiffLineTypeToStr, + "Sha1": Sha1, "ShortSha": ShortSha, "Md5": EncodeMd5, "ActionContent2Commits": ActionContent2Commits, diff --git a/public/ng/js/gogs.js b/public/ng/js/gogs.js index a6b9753e1..bd320b440 100644 --- a/public/ng/js/gogs.js +++ b/public/ng/js/gogs.js @@ -209,14 +209,14 @@ var Gogs = {}; $list.parents('tr').removeClass('end-selected-line'); $list.parents('tr').find('td').removeClass('selected-line'); if ($from) { - var expr = new RegExp(/diff-(\d+)L(\d+)/); + var expr = new RegExp(/diff-(\w+)([LR])(\d+)/); var selectMatches = $select.attr('rel').match(expr) var fromMatches = $from.attr('rel').match(expr) - var a = parseInt(selectMatches[2]); - var b = parseInt(fromMatches[2]); + var a = parseInt(selectMatches[3]); + var b = parseInt(fromMatches[3]); var linesIntToStr = {}; - linesIntToStr[a] = selectMatches[2]; - linesIntToStr[b] = fromMatches[2]; + linesIntToStr[a] = selectMatches[3]; + linesIntToStr[b] = fromMatches[3]; var c; if (a != b) { @@ -225,11 +225,11 @@ var Gogs = {}; a = b; b = c; } - $('[rel=diff-'+fromMatches[1]+'L' + linesIntToStr[b] + ']').parents('tr').next().addClass('end-selected-line'); - var $selectedLines = $('[rel=diff-'+fromMatches[1]+'L' + linesIntToStr[a] + ']').parents('tr').nextUntil('.end-selected-line').andSelf(); + $('[rel=diff-'+fromMatches[1] + fromMatches[2] + linesIntToStr[b] + ']').parents('tr').next().addClass('end-selected-line'); + var $selectedLines = $('[rel=diff-'+fromMatches[1]+selectMatches[2] + linesIntToStr[a] + ']').parents('tr').nextUntil('.end-selected-line').andSelf(); $selectedLines.find('td.lines-num > span').addClass('active') $selectedLines.find('td').addClass('selected-line'); - $.changeHash('#diff-'+fromMatches[1]+'L' + linesIntToStr[a] + '-L' + linesIntToStr[b]); + $.changeHash('#diff-'+fromMatches[1]+fromMatches[2] + linesIntToStr[a] + '-' + selectMatches[2] + + linesIntToStr[b]); return } } @@ -262,7 +262,7 @@ var Gogs = {}; }); $(window).on('hashchange', function (e) { - var m = window.location.hash.match(/^#diff-(\d+)(L\d+)\-(L\d+)$/); + var m = window.location.hash.match(/^#diff-(\w+)([LR]\d+)\-([LR]\d+)$/); var $list = $('.code-diff td.lines-num > span'); var $first; if (m) { @@ -271,7 +271,7 @@ var Gogs = {}; $("html, body").scrollTop($first.offset().top - 200); return; } - m = window.location.hash.match(/^#diff-(\d+)(L\d+)$/); + m = window.location.hash.match(/^#diff-(\w+)([LR]\d+)$/); if (m) { $first = $list.filter('[rel=diff-' + m[1] + m[2] + ']'); selectRange($list, $first); diff --git a/templates/repo/diff.tmpl b/templates/repo/diff.tmpl index 443e002d5..2bc5c7d7d 100644 --- a/templates/repo/diff.tmpl +++ b/templates/repo/diff.tmpl @@ -106,13 +106,13 @@ {{range $j, $section := $file.Sections}} - {{range $k, $line := $section.Lines}} + {{range $k, $line := $section.Lines}}
    - {{if $line.LeftIdx}}{{$line.LeftIdx}}{{end}} + {{if $line.LeftIdx}}{{$line.LeftIdx}}{{end}} - {{if $line.RightIdx}}{{$line.RightIdx}}{{end}} + {{if $line.RightIdx}}{{$line.RightIdx}}{{end}} From c0ad512398e0d8232f5e729f2c38e887e6d9329a Mon Sep 17 00:00:00 2001 From: Alexey Makhov Date: Thu, 19 Feb 2015 00:55:17 +0300 Subject: [PATCH 16/30] remove not using vars --- templates/repo/diff.tmpl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/templates/repo/diff.tmpl b/templates/repo/diff.tmpl index 2bc5c7d7d..7da932a4f 100644 --- a/templates/repo/diff.tmpl +++ b/templates/repo/diff.tmpl @@ -105,9 +105,9 @@ {{else}} - {{range $j, $section := $file.Sections}} - {{range $k, $line := $section.Lines}} - + {{range .Sections}} + {{range $k, $line := .Lines}} + From d2f439a2410259dcce96889a02c7a6bbf64d385e Mon Sep 17 00:00:00 2001 From: Alexey Makhov Date: Thu, 19 Feb 2015 10:19:10 +0300 Subject: [PATCH 17/30] fix typo mistake --- templates/repo/diff.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/repo/diff.tmpl b/templates/repo/diff.tmpl index 7da932a4f..f261da55a 100644 --- a/templates/repo/diff.tmpl +++ b/templates/repo/diff.tmpl @@ -109,7 +109,7 @@ {{range $k, $line := .Lines}}
    {{if $line.LeftIdx}}{{$line.LeftIdx}}{{end}}
    - {{if $line.LeftIdx}}{{$line.LeftIdx}}{{end}} + {{if $line.LeftIdx}}{{$line.LeftIdx}}{{end}} {{if $line.RightIdx}}{{$line.RightIdx}}{{end}} From 5293ae1221988d5cd0329d2a980612fb7e4df3a7 Mon Sep 17 00:00:00 2001 From: Gogs Date: Thu, 19 Feb 2015 10:47:05 +0300 Subject: [PATCH 18/30] Fix: 504 5.5.2 : Helo command rejected --- modules/mailer/mailer.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/modules/mailer/mailer.go b/modules/mailer/mailer.go index 6a23e5d09..57400e73f 100644 --- a/modules/mailer/mailer.go +++ b/modules/mailer/mailer.go @@ -10,6 +10,7 @@ import ( "net" "net/mail" "net/smtp" + "os" "strings" "github.com/gogits/gogs/modules/log" @@ -95,6 +96,12 @@ func sendMail(settings *setting.Mailer, recipients []string, msgContent []byte) return err } + hostname, err := os.Hostname() + if err != nil { + return err + } + client.Hello(hostname) + // If not using SMTPS, alway use STARTTLS if available hasStartTLS, _ := client.Extension("STARTTLS") if !isSecureConn && hasStartTLS { From 3efe3f42e80a2fd5dfff639be120b2bc5cf28474 Mon Sep 17 00:00:00 2001 From: Alexey Makhov Date: Thu, 19 Feb 2015 11:08:47 +0300 Subject: [PATCH 19/30] js fix R1-L1 highlight --- public/ng/js/gogs.js | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/public/ng/js/gogs.js b/public/ng/js/gogs.js index bd320b440..c5fd719c3 100644 --- a/public/ng/js/gogs.js +++ b/public/ng/js/gogs.js @@ -209,27 +209,28 @@ var Gogs = {}; $list.parents('tr').removeClass('end-selected-line'); $list.parents('tr').find('td').removeClass('selected-line'); if ($from) { - var expr = new RegExp(/diff-(\w+)([LR])(\d+)/); + var expr = new RegExp(/diff-(\w+)([LR]\d+)/); var selectMatches = $select.attr('rel').match(expr) var fromMatches = $from.attr('rel').match(expr) - var a = parseInt(selectMatches[3]); - var b = parseInt(fromMatches[3]); - var linesIntToStr = {}; - linesIntToStr[a] = selectMatches[3]; - linesIntToStr[b] = fromMatches[3]; + var selectTop = $select.offset().top; + var fromTop = $from.offset().top; + var hash; - var c; - if (a != b) { - if (a > b) { - c = a; - a = b; - b = c; + if (selectMatches[2] != fromMatches[2]) { + if ((selectTop > fromTop)) { + $startElem = $from; + $endElem = $select; + hash = fromMatches[1]+fromMatches[2] + '-' + selectMatches[2]; + } else { + $startElem = $select; + $endElem = $from; + hash = selectMatches[1]+selectMatches[2] + '-' + fromMatches[2]; } - $('[rel=diff-'+fromMatches[1] + fromMatches[2] + linesIntToStr[b] + ']').parents('tr').next().addClass('end-selected-line'); - var $selectedLines = $('[rel=diff-'+fromMatches[1]+selectMatches[2] + linesIntToStr[a] + ']').parents('tr').nextUntil('.end-selected-line').andSelf(); + $endElem.parents('tr').next().addClass('end-selected-line'); + var $selectedLines = $startElem.parents('tr').nextUntil('.end-selected-line').andSelf(); $selectedLines.find('td.lines-num > span').addClass('active') $selectedLines.find('td').addClass('selected-line'); - $.changeHash('#diff-'+fromMatches[1]+fromMatches[2] + linesIntToStr[a] + '-' + selectMatches[2] + + linesIntToStr[b]); + $.changeHash('#diff-'+hash); return } } From 2f1369c6147b51d0c5f82a3d236d69ac100ef8e8 Mon Sep 17 00:00:00 2001 From: Gogs Date: Fri, 20 Feb 2015 10:12:27 +0300 Subject: [PATCH 20/30] add error for hello func --- modules/mailer/mailer.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/mailer/mailer.go b/modules/mailer/mailer.go index 57400e73f..fc6ec2fa8 100644 --- a/modules/mailer/mailer.go +++ b/modules/mailer/mailer.go @@ -100,7 +100,10 @@ func sendMail(settings *setting.Mailer, recipients []string, msgContent []byte) if err != nil { return err } - client.Hello(hostname) + + if err = client.Hello(hostname); err != nil { + return err + } // If not using SMTPS, alway use STARTTLS if available hasStartTLS, _ := client.Extension("STARTTLS") From 4f567edc6edbe8f43e6acd54bc3fe4e579b2389a Mon Sep 17 00:00:00 2001 From: Raphael Randschau Date: Fri, 20 Feb 2015 07:52:56 +0100 Subject: [PATCH 21/30] Fix #933 Not sure why, but xorm ignores the num_issues and num_closed_issues columns when updating, even though the values changed. Listing them explicitly fixes the issue with the wrong issue counts --- models/issue.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/models/issue.go b/models/issue.go index d9a24063c..226ca3ca5 100644 --- a/models/issue.go +++ b/models/issue.go @@ -561,7 +561,7 @@ func GetLabels(repoId int64) ([]*Label, error) { // UpdateLabel updates label information. func UpdateLabel(l *Label) error { - _, err := x.Id(l.Id).Update(l) + _, err := x.Id(l.Id).AllCols().Update(l) return err } From 1654e9ecab3923b7fe5d528fc86c1a549546bd29 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Sat, 21 Feb 2015 22:13:47 -0500 Subject: [PATCH 22/30] templates/user/settings/emial.tmpl: little fix on UI - routers/user: little code format - conf/locale: update French locale --- conf/locale/locale_fr-CA.ini | 16 +++--- gogs.go | 2 +- models/user.go | 9 ++-- modules/auth/user_form.go | 2 +- routers/user/auth.go | 5 +- routers/user/setting.go | 80 ++++++++++++++---------------- templates/.VERSION | 2 +- templates/user/settings/email.tmpl | 6 +-- 8 files changed, 58 insertions(+), 64 deletions(-) diff --git a/conf/locale/locale_fr-CA.ini b/conf/locale/locale_fr-CA.ini index 0aeae3423..e744b9d97 100755 --- a/conf/locale/locale_fr-CA.ini +++ b/conf/locale/locale_fr-CA.ini @@ -59,8 +59,8 @@ run_user=Entrer un Utilisateur run_user_helper=L'utilisateur doit avoir accès à la Racine du Référentiel et éxécuter Gogs. domain=Domaine domain_helper=Cela affecte les doublons d'URL SSH. -http_port=HTTP Port -http_port_helper=Port number which application will listen on. +http_port=Port HTTP +http_port_helper=Numéro de port que l'application écoutera. app_url=URL de l'Application app_url_helper=Cela affecte les doublons d'URL HTTP/HTTPS et le contenu d'e-mail. email_title=Paramètres du Service de Messagerie (Facultatif) @@ -514,10 +514,10 @@ dashboard.delete_repo_archives=Supprimer toutes les archives de référentiels dashboard.delete_repo_archives_success=Toutes les archives de référentiels ont été supprimés avec succès. dashboard.git_gc_repos=Collecter les déchets des référentiels dashboard.git_gc_repos_success=Tous les référentiels ont effectué la collecte avec succès. -dashboard.resync_all_sshkeys=Rewrite '.ssh/autorized_key' file (caution: non-Gogs keys will be lost) -dashboard.resync_all_sshkeys_success=All public keys have been rewritten successfully. -dashboard.resync_all_update_hooks=Rewrite all update hook of repositories (needed when custom config path is changed) -dashboard.resync_all_update_hooks_success=All repositories' update hook have been rewritten successfully. +dashboard.resync_all_sshkeys=Ré-écrire le fichier '.ssh/autorized_key' (attention : les clés hors-Gogs vont être perdues) +dashboard.resync_all_sshkeys_success=Toutes les clés publiques ont été ré-écrites avec succès. +dashboard.resync_all_update_hooks=Ré-écrire tous les hooks de mises à jour des dépôts (requis quand le chemin de la configuration personnalisé est modifié) +dashboard.resync_all_update_hooks_success=Tous les hooks de mises à jour des dépôts ont été ré-écris avec succès. dashboard.server_uptime=Durée de Marche Serveur dashboard.current_goroutine=Goroutines actuelles @@ -638,7 +638,7 @@ config.db_path_helper=("sqlite3" uniquement) config.service_config=Configuration du Service config.register_email_confirm=Nécessite une confirmation par courriel config.disable_register=Désactiver l'Enregistrement -config.show_registration_button=Show Register Button +config.show_registration_button=Afficher le bouton d'enregistrement config.require_sign_in_view=Connexion Obligatoire pour Visualiser config.mail_notify=Mailer les Notifications config.enable_cache_avatar=Activer le Cache d'Avatar @@ -647,7 +647,7 @@ config.reset_password_code_lives=Réinitialiser le Mot De Passe des Limites de C config.webhook_config=Configuration Webhook config.task_interval=Intervalles de Tâches config.deliver_timeout=Expiration d'Envoi -config.skip_tls_verify=Skip TLS Verify +config.skip_tls_verify=Ne pas vérifier TLS config.mailer_config=Configuration du Maileur config.mailer_enabled=Activé config.mailer_name=Nom diff --git a/gogs.go b/gogs.go index 34790b725..5c24e229a 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.5.13.0214 Beta" +const APP_VER = "0.5.14.0221 Beta" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/user.go b/models/user.go index 2da0881c8..9f9b0cd7f 100644 --- a/models/user.go +++ b/models/user.go @@ -627,7 +627,7 @@ func GetUserIdsByNames(names []string) []int64 { return ids } -// Get all email addresses +// GetEmailAddresses returns all e-mail addresses belongs to given user. func GetEmailAddresses(uid int64) ([]*EmailAddress, error) { emails := make([]*EmailAddress, 0, 5) err := x.Where("uid=?", uid).Find(&emails) @@ -641,7 +641,6 @@ func GetEmailAddresses(uid int64) ([]*EmailAddress, error) { } isPrimaryFound := false - for _, email := range emails { if email.Email == u.Email { isPrimaryFound = true @@ -654,7 +653,11 @@ func GetEmailAddresses(uid int64) ([]*EmailAddress, error) { // We alway want the primary email address displayed, even if it's not in // the emailaddress table (yet) if !isPrimaryFound { - emails = append(emails, &EmailAddress{Email: u.Email, IsActivated: true, IsPrimary: true}) + emails = append(emails, &EmailAddress{ + Email: u.Email, + IsActivated: true, + IsPrimary: true, + }) } return emails, nil } diff --git a/modules/auth/user_form.go b/modules/auth/user_form.go index 3c0ff6517..b616a460f 100644 --- a/modules/auth/user_form.go +++ b/modules/auth/user_form.go @@ -99,7 +99,7 @@ func (f *UploadAvatarForm) Validate(ctx *macaron.Context, errs binding.Errors) b } type AddEmailForm struct { - Email string `form:"email" binding:"Required;Email;MaxSize(50)"` + Email string `binding:"Required;Email;MaxSize(50)"` } func (f *AddEmailForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { diff --git a/routers/user/auth.go b/routers/user/auth.go index 9ed44e353..5dacaf8c7 100644 --- a/routers/user/auth.go +++ b/routers/user/auth.go @@ -351,15 +351,12 @@ func ActivateEmail(ctx *middleware.Context) { // Verify code. if email := models.VerifyActiveEmailCode(code, email_string); email != nil { - err := email.Activate() - if err != nil { + if err := email.Activate(); err != nil { ctx.Handle(500, "ActivateEmail", err) } log.Trace("Email activated: %s", email.Email) - ctx.Flash.Success(ctx.Tr("settings.activate_email_success")) - } ctx.Redirect(setting.AppSubUrl + "/user/settings/email") diff --git a/routers/user/setting.go b/routers/user/setting.go index 953e61138..9398f69a0 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -133,13 +133,12 @@ func SettingsEmails(ctx *middleware.Context) { ctx.Data["PageIsUserSettings"] = true ctx.Data["PageIsSettingsEmails"] = true - var err error - ctx.Data["Emails"], err = models.GetEmailAddresses(ctx.User.Id) - + emails, err := models.GetEmailAddresses(ctx.User.Id) if err != nil { - ctx.Handle(500, "email.GetEmailAddresses", err) + ctx.Handle(500, "GetEmailAddresses", err) return } + ctx.Data["Emails"] = emails ctx.HTML(200, SETTINGS_EMAILS) } @@ -149,16 +148,16 @@ func SettingsEmailPost(ctx *middleware.Context, form auth.AddEmailForm) { ctx.Data["PageIsUserSettings"] = true ctx.Data["PageIsSettingsEmails"] = true - var err error - ctx.Data["Emails"], err = models.GetEmailAddresses(ctx.User.Id) + emails, err := models.GetEmailAddresses(ctx.User.Id) if err != nil { - ctx.Handle(500, "email.GetEmailAddresses", err) + ctx.Handle(500, "GetEmailAddresses", err) return } + ctx.Data["Emails"] = emails - // Delete Email address. + // Delete E-mail address. if ctx.Query("_method") == "DELETE" { - id := com.StrTo(ctx.Query("id")).MustInt64() + id := ctx.QueryInt64("id") if id <= 0 { return } @@ -174,7 +173,7 @@ func SettingsEmailPost(ctx *middleware.Context, form auth.AddEmailForm) { // Make emailaddress primary. if ctx.Query("_method") == "PRIMARY" { - id := com.StrTo(ctx.Query("id")).MustInt64() + id := ctx.QueryInt64("id") if id <= 0 { return } @@ -189,46 +188,41 @@ func SettingsEmailPost(ctx *middleware.Context, form auth.AddEmailForm) { } // Add Email address. - if ctx.Req.Method == "POST" { - if ctx.HasError() { - ctx.HTML(200, SETTINGS_EMAILS) + if ctx.HasError() { + ctx.HTML(200, SETTINGS_EMAILS) + return + } + + cleanEmail := strings.Replace(form.Email, "\n", "", -1) + e := &models.EmailAddress{ + Uid: ctx.User.Id, + Email: cleanEmail, + IsActivated: !setting.Service.RegisterEmailConfirm, + } + + if err := models.AddEmailAddress(e); err != nil { + if err == models.ErrEmailAlreadyUsed { + ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SETTINGS_EMAILS, &form) return } + ctx.Handle(500, "AddEmailAddress", err) + return + } else { + // Send confirmation e-mail + if setting.Service.RegisterEmailConfirm { + mailer.SendActivateEmail(ctx.Render, ctx.User, e) - cleanEmail := strings.Replace(form.Email, "\n", "", -1) - e := &models.EmailAddress{ - Uid: ctx.User.Id, - Email: cleanEmail, - IsActivated: !setting.Service.RegisterEmailConfirm, - } - - if err := models.AddEmailAddress(e); err != nil { - if err == models.ErrEmailAlreadyUsed { - ctx.RenderWithErr(ctx.Tr("form.email_has_been_used"), SETTINGS_EMAILS, &form) - return + if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil { + log.Error(4, "Set cache(MailResendLimit) fail: %v", err) } - ctx.Handle(500, "email.AddEmailAddress", err) - return + ctx.Flash.Success(ctx.Tr("settings.add_email_success_confirmation_email_sent")) } else { - - // Send confirmation e-mail - if setting.Service.RegisterEmailConfirm { - mailer.SendActivateEmail(ctx.Render, ctx.User, e) - - if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil { - log.Error(4, "Set cache(MailResendLimit) fail: %v", err) - } - ctx.Flash.Success(ctx.Tr("settings.add_email_success_confirmation_email_sent")) - } else { - ctx.Flash.Success(ctx.Tr("settings.add_email_success")) - } - - log.Trace("Email address added: %s", e.Email) - - ctx.Redirect(setting.AppSubUrl + "/user/settings/email") - return + ctx.Flash.Success(ctx.Tr("settings.add_email_success")) } + log.Trace("Email address added: %s", e.Email) + ctx.Redirect(setting.AppSubUrl + "/user/settings/email") + return } ctx.HTML(200, SETTINGS_EMAILS) diff --git a/templates/.VERSION b/templates/.VERSION index 0c9421a4d..489addf9a 100644 --- a/templates/.VERSION +++ b/templates/.VERSION @@ -1 +1 @@ -0.5.13.0214 Beta \ No newline at end of file +0.5.14.0221 Beta \ No newline at end of file diff --git a/templates/user/settings/email.tmpl b/templates/user/settings/email.tmpl index c99e6a041..ec152c5d6 100644 --- a/templates/user/settings/email.tmpl +++ b/templates/user/settings/email.tmpl @@ -16,7 +16,7 @@ {{range .Emails}} From 9dfa17faf28685c8afc24e91570a56d256c701be Mon Sep 17 00:00:00 2001 From: Unknwon Date: Sat, 21 Feb 2015 23:37:32 -0500 Subject: [PATCH 23/30] modules/git: able to parse RFC1123Z date format #663 --- modules/git/signature.go | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/modules/git/signature.go b/modules/git/signature.go index 20f647d26..ad9c1b39b 100644 --- a/modules/git/signature.go +++ b/modules/git/signature.go @@ -17,24 +17,35 @@ type Signature struct { When time.Time } -// Helper to get a signature from the commit line, which looks like this: +// Helper to get a signature from the commit line, which looks like these: // author Patrick Gundlach 1378823654 +0200 +// author Patrick Gundlach Thu, 07 Apr 2005 22:13:13 +0200 // but without the "author " at the beginning (this method should) // be used for author and committer. // -// FIXME: include timezone! -func newSignatureFromCommitline(line []byte) (*Signature, error) { +// FIXME: include timezone for timestamp! +func newSignatureFromCommitline(line []byte) (_ *Signature, err error) { sig := new(Signature) emailstart := bytes.IndexByte(line, '<') sig.Name = string(line[:emailstart-1]) emailstop := bytes.IndexByte(line, '>') sig.Email = string(line[emailstart+1 : emailstop]) - timestop := bytes.IndexByte(line[emailstop+2:], ' ') - timestring := string(line[emailstop+2 : emailstop+2+timestop]) - seconds, err := strconv.ParseInt(timestring, 10, 64) - if err != nil { - return nil, err + + // Check date format. + firstChar := line[emailstop+2] + if firstChar >= 48 && firstChar <= 57 { + timestop := bytes.IndexByte(line[emailstop+2:], ' ') + timestring := string(line[emailstop+2 : emailstop+2+timestop]) + seconds, err := strconv.ParseInt(timestring, 10, 64) + if err != nil { + return nil, err + } + sig.When = time.Unix(seconds, 0) + } else { + sig.When, err = time.Parse(time.RFC1123Z, string(line[emailstop+2:])) + if err != nil { + return nil, err + } } - sig.When = time.Unix(seconds, 0) return sig, nil } From a6a99d49cf98575a4792caffeb412737c58d4099 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Sun, 22 Feb 2015 00:12:55 -0500 Subject: [PATCH 24/30] reword --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc21ee038..411a8e931 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -52,7 +52,7 @@ We're trying very hard to keep Gogs lean and focused. We don't want it to do eve ### Ask For Help -Before opening a new issue, please check to make sure your problem isn't already addressed on the [Troubleshooting](http://gogs.io/docs/intro/troubleshooting.md) and [FAQs](http://gogs.io/docs/intro/faqs.html) pages. +Before opening an issue, please make sure your problem isn't already addressed on the [Troubleshooting](http://gogs.io/docs/intro/troubleshooting.md) and [FAQs](http://gogs.io/docs/intro/faqs.html) pages. ## Things To Notice From c753fdceaf0549aa865cff4e1f42be5d907bbdb1 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Sun, 22 Feb 2015 03:07:04 -0500 Subject: [PATCH 25/30] templates/org/home.tmpl: fix org member can't see public repo --- gogs.go | 2 +- templates/.VERSION | 2 +- templates/org/home.tmpl | 140 ++++++++++++++++++++-------------------- 3 files changed, 72 insertions(+), 72 deletions(-) diff --git a/gogs.go b/gogs.go index 5c24e229a..b2366b634 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.5.14.0221 Beta" +const APP_VER = "0.5.14.0222 Beta" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/templates/.VERSION b/templates/.VERSION index 489addf9a..b9cd4a186 100644 --- a/templates/.VERSION +++ b/templates/.VERSION @@ -1 +1 @@ -0.5.14.0221 Beta \ No newline at end of file +0.5.14.0222 Beta \ No newline at end of file diff --git a/templates/org/home.tmpl b/templates/org/home.tmpl index bb160b57b..df29d61fc 100644 --- a/templates/org/home.tmpl +++ b/templates/org/home.tmpl @@ -9,85 +9,85 @@ {{if .IsOrganizationOwner}}{{end}} {{if .Org.Description}}

    {{.Org.Description}}

    {{end}} - +
    {{$isMember := .Org.IsOrgMember $.SignedUser.Id}} -
    -
    - {{if .IsOrganizationOwner}} - {{.i18n.Tr "new_repo"}} - {{end}} -
    -
    - {{range .Repos}} - {{if .HasAccess $.SignedUser.Name}} -
    -
      -
    • {{.NumStars}}
    • -
    • {{.NumForks}}
    • -
    -

    {{.Name}}

    -

    {{.Description}}

    -

    {{$.i18n.Tr "org.repo_updated"}} {{TimeSince .Updated $.i18n.Lang}}

    -
    - {{end}} +
    +
    + {{if .IsOrganizationOwner}} + {{.i18n.Tr "new_repo"}} + {{end}} +
    +
    + {{range .Repos}} + {{if or (not .IsPrivate) (.HasAccess $.SignedUser.Name)}} +
    +
      +
    • {{.NumStars}}
    • +
    • {{.NumForks}}
    • +
    +

    {{.Name}}

    +

    {{.Description}}

    +

    {{$.i18n.Tr "org.repo_updated"}} {{TimeSince .Updated $.i18n.Lang}}

    +
    {{end}} -
    + {{end}}
    -
    -
    -
    -
    - {{if $isMember}} - {{.Org.NumMembers}} - {{end}} - {{.i18n.Tr "org.people"}} -
    -
    - {{range .Members}} +
    +
    +
    +
    +
    + {{if $isMember}} + {{.Org.NumMembers}} + {{end}} + {{.i18n.Tr "org.people"}} +
    +
    + {{range .Members}} {{if or $isMember (.IsPublicMember $.Org.Id)}} - - {{end}} + {{end}} -
    - {{if .IsOrganizationOwner}} - - {{end}} -
    - {{if $isMember}} -
    -
    -
    - {{.Org.NumTeams}} - {{.i18n.Tr "org.teams"}} -
    -
    -
      - {{range .Teams}} -
    • - {{.Name}} -

      {{.NumMembers}} {{$.i18n.Tr "org.lower_members"}} · {{.NumRepos}} {{$.i18n.Tr "org.lower_repositories"}}

      -
    • - {{end}} -
    -
    - {{if .IsOrganizationOwner}} - - {{end}} -
    - {{end}} + {{end}} +
    + {{if .IsOrganizationOwner}} + + {{end}}
    -
    + {{if $isMember}} +
    +
    +
    + {{.Org.NumTeams}} + {{.i18n.Tr "org.teams"}} +
    +
    +
      + {{range .Teams}} +
    • + {{.Name}} +

      {{.NumMembers}} {{$.i18n.Tr "org.lower_members"}} · {{.NumRepos}} {{$.i18n.Tr "org.lower_repositories"}}

      +
    • + {{end}} +
    +
    + {{if .IsOrganizationOwner}} + + {{end}} +
    + {{end}} +
    +
    {{template "ng/base/footer" .}} \ No newline at end of file From 81fcc0db0c2ae8ed84931995e505076e8227948c Mon Sep 17 00:00:00 2001 From: Alban Garrigue Date: Sun, 22 Feb 2015 13:06:46 +0100 Subject: [PATCH 26/30] $DIRECTORY variable is never set --- docker/templates/init_gogs.sh.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/templates/init_gogs.sh.tpl b/docker/templates/init_gogs.sh.tpl index 26cff4e50..ada11f95a 100644 --- a/docker/templates/init_gogs.sh.tpl +++ b/docker/templates/init_gogs.sh.tpl @@ -1,6 +1,6 @@ #!/bin/sh -if [ ! -d "$DIRECTORY" ]; then +if [ ! -d "$GOGS_CUSTOM_CONF_PATH" ]; then mkdir -p $GOGS_CUSTOM_CONF_PATH echo " From 059338139ca4a70cb1138dc09039abb5dac0d0f2 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Sun, 22 Feb 2015 09:49:25 -0500 Subject: [PATCH 27/30] routers: able to migrate repo from local path - modules/middleware/context.go: add HandleAPI method --- cmd/web.go | 4 +- conf/locale/locale_en-US.ini | 2 + modules/auth/repo_form.go | 2 +- modules/middleware/context.go | 12 ++++++ routers/api/v1/repo.go | 75 ++++++++++++++++++----------------- routers/repo/repo.go | 28 ++++++++----- templates/repo/migrate.tmpl | 4 +- 7 files changed, 74 insertions(+), 53 deletions(-) diff --git a/cmd/web.go b/cmd/web.go index 4b06a882c..1b692ceb4 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -79,7 +79,7 @@ func checkVersion() { // Check dependency version. checkers := []VerChecker{ {"github.com/Unknwon/macaron", macaron.Version, "0.5.1"}, - {"github.com/macaron-contrib/binding", binding.Version, "0.0.4"}, + {"github.com/macaron-contrib/binding", binding.Version, "0.0.5"}, {"github.com/macaron-contrib/cache", cache.Version, "0.0.7"}, {"github.com/macaron-contrib/csrf", csrf.Version, "0.0.3"}, {"github.com/macaron-contrib/i18n", i18n.Version, "0.0.5"}, @@ -229,7 +229,7 @@ func runWeb(ctx *cli.Context) { }) m.Any("/*", func(ctx *middleware.Context) { - ctx.JSON(404, &base.ApiJsonErr{"Not Found", base.DOC_URL}) + ctx.HandleAPI(404, "Page not found") }) }) }) diff --git a/conf/locale/locale_en-US.ini b/conf/locale/locale_en-US.ini index 54b80abb5..ca076b8bb 100644 --- a/conf/locale/locale_en-US.ini +++ b/conf/locale/locale_en-US.ini @@ -286,6 +286,8 @@ need_auth = Need Authorization migrate_type = Migration Type migrate_type_helper = This repository will be a Mirror migrate_repo = Migrate Repository +migrate.clone_address = Clone Address +migrate.invalid_local_path = Invalid local path, it does not exist or not a directory. copy_link = Copy click_to_copy = Copy to clipboard diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index c771dd59b..2902a92f2 100644 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -31,7 +31,7 @@ func (f *CreateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) bin } type MigrateRepoForm struct { - HttpsUrl string `form:"url" binding:"Required;Url"` + CloneAddr string `binding:"Required"` AuthUserName string `form:"auth_username"` AuthPasswd string `form:"auth_password"` Uid int64 `form:"uid" binding:"Required"` diff --git a/modules/middleware/context.go b/modules/middleware/context.go index 28be3a302..45779d580 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -130,6 +130,18 @@ func (ctx *Context) Handle(status int, title string, err error) { ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status))) } +func (ctx *Context) HandleAPI(status int, obj interface{}) { + var message string + if err, ok := obj.(error); ok { + message = err.Error() + } else { + message = obj.(string) + } + ctx.JSON(status, map[string]string{ + "message": message, + }) +} + func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) { modtime := time.Now() for _, p := range params { diff --git a/routers/api/v1/repo.go b/routers/api/v1/repo.go index fbf9c73ea..fde184d99 100644 --- a/routers/api/v1/repo.go +++ b/routers/api/v1/repo.go @@ -5,7 +5,7 @@ package v1 import ( - "fmt" + "net/url" "path" "strings" @@ -156,17 +156,15 @@ func CreateOrgRepo(ctx *middleware.Context, opt api.CreateRepoOption) { func MigrateRepo(ctx *middleware.Context, form auth.MigrateRepoForm) { u, err := models.GetUserByName(ctx.Query("username")) if err != nil { - ctx.JSON(500, map[string]interface{}{ - "ok": false, - "error": err.Error(), - }) + if err == models.ErrUserNotExist { + ctx.HandleAPI(422, err) + } else { + ctx.HandleAPI(500, err) + } return } if !u.ValidtePassword(ctx.Query("password")) { - ctx.JSON(500, map[string]interface{}{ - "ok": false, - "error": "username or password is not correct", - }) + ctx.HandleAPI(422, "Username or password is not correct.") return } @@ -175,56 +173,59 @@ func MigrateRepo(ctx *middleware.Context, form auth.MigrateRepoForm) { if form.Uid != u.Id { org, err := models.GetUserById(form.Uid) if err != nil { - log.Error(4, "GetUserById: %v", err) - ctx.Error(500) + if err == models.ErrUserNotExist { + ctx.HandleAPI(422, err) + } else { + ctx.HandleAPI(500, err) + } return } ctxUser = org } if ctx.HasError() { - ctx.JSON(422, map[string]interface{}{ - "ok": false, - "error": ctx.GetErrMsg(), - }) + ctx.HandleAPI(422, ctx.GetErrMsg()) return } if ctxUser.IsOrganization() { // Check ownership of organization. if !ctxUser.IsOwnedBy(u.Id) { - ctx.JSON(403, map[string]interface{}{ - "ok": false, - "error": "given user is not owner of organization", - }) + ctx.HandleAPI(403, "Given user is not owner of organization.") return } } - authStr := strings.Replace(fmt.Sprintf("://%s:%s", - form.AuthUserName, form.AuthPasswd), "@", "%40", -1) - url := strings.Replace(form.HttpsUrl, "://", authStr+"@", 1) - repo, err := models.MigrateRepository(ctxUser, form.RepoName, form.Description, form.Private, - form.Mirror, url) - if err == nil { - log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName) - ctx.JSON(200, map[string]interface{}{ - "ok": true, - "data": "/" + ctxUser.Name + "/" + form.RepoName, - }) + // Remote address can be HTTPS URL or local path. + remoteAddr := form.CloneAddr + if strings.HasPrefix(form.CloneAddr, "http") { + u, err := url.Parse(form.CloneAddr) + if err != nil { + ctx.HandleAPI(422, err) + return + } + if len(form.AuthUserName) > 0 || len(form.AuthPasswd) > 0 { + u.User = url.UserPassword(form.AuthUserName, form.AuthPasswd) + } + remoteAddr = u.String() + } else if !com.IsDir(remoteAddr) { + ctx.HandleAPI(422, "Invalid local path, it does not exist or not a directory.") return } - if repo != nil { - if errDelete := models.DeleteRepository(ctxUser.Id, repo.Id, ctxUser.Name); errDelete != nil { - log.Error(4, "DeleteRepository: %v", errDelete) + repo, err := models.MigrateRepository(ctxUser, form.RepoName, form.Description, form.Private, form.Mirror, remoteAddr) + if err != nil { + if repo != nil { + if errDelete := models.DeleteRepository(ctxUser.Id, repo.Id, ctxUser.Name); errDelete != nil { + log.Error(4, "DeleteRepository: %v", errDelete) + } } + ctx.HandleAPI(500, err) + return } - ctx.JSON(500, map[string]interface{}{ - "ok": false, - "error": err.Error(), - }) + log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName) + ctx.WriteHeader(200) } // GET /user/repos diff --git a/routers/repo/repo.go b/routers/repo/repo.go index 48f7b09bc..dfd827bbb 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -181,20 +181,26 @@ func MigratePost(ctx *middleware.Context, form auth.MigrateRepoForm) { } } - u, err := url.Parse(form.HttpsUrl) - - if err != nil || u.Scheme != "https" { - ctx.Data["Err_HttpsUrl"] = true - ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &form) + // Remote address can be HTTPS URL or local path. + remoteAddr := form.CloneAddr + if strings.HasPrefix(form.CloneAddr, "http") { + u, err := url.Parse(form.CloneAddr) + if err != nil { + ctx.Data["Err_CloneAddr"] = true + ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &form) + return + } + if len(form.AuthUserName) > 0 || len(form.AuthPasswd) > 0 { + u.User = url.UserPassword(form.AuthUserName, form.AuthPasswd) + } + remoteAddr = u.String() + } else if !com.IsDir(remoteAddr) { + ctx.Data["Err_CloneAddr"] = true + ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), MIGRATE, &form) return } - if len(form.AuthUserName) > 0 || len(form.AuthPasswd) > 0 { - u.User = url.UserPassword(form.AuthUserName, form.AuthPasswd) - } - - repo, err := models.MigrateRepository(ctxUser, form.RepoName, form.Description, form.Private, - form.Mirror, u.String()) + repo, err := models.MigrateRepository(ctxUser, form.RepoName, form.Description, form.Private, form.Mirror, remoteAddr) if err == nil { log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName) ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + form.RepoName) diff --git a/templates/repo/migrate.tmpl b/templates/repo/migrate.tmpl index b28d06475..5869be155 100644 --- a/templates/repo/migrate.tmpl +++ b/templates/repo/migrate.tmpl @@ -7,8 +7,8 @@
    {{template "ng/base/alert" .}}
    - - + +
    From 7d109573cbed38084ae8019c57375735d2296b56 Mon Sep 17 00:00:00 2001 From: Alban Garrigue Date: Sun, 22 Feb 2015 16:42:59 +0100 Subject: [PATCH 28/30] openssh-client provide ssh-keygen. GOGS needs that binary to add a ssh key to a user --- docker/blocks/docker_gogs/Dockerfile | 2 +- docker/blocks/docker_gogs_dev/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker/blocks/docker_gogs/Dockerfile b/docker/blocks/docker_gogs/Dockerfile index 2c98cc501..efedc31a8 100644 --- a/docker/blocks/docker_gogs/Dockerfile +++ b/docker/blocks/docker_gogs/Dockerfile @@ -4,7 +4,7 @@ FROM ubuntu:14.04 RUN apt-get update && apt-get install -y \ build-essential ca-certificates curl \ - bzr git mercurial \ + bzr git mercurial openssh-client\ --no-install-recommends ENV GOLANG_VERSION 1.3 diff --git a/docker/blocks/docker_gogs_dev/Dockerfile b/docker/blocks/docker_gogs_dev/Dockerfile index 2a628c2d5..ce653fbe7 100644 --- a/docker/blocks/docker_gogs_dev/Dockerfile +++ b/docker/blocks/docker_gogs_dev/Dockerfile @@ -5,7 +5,7 @@ FROM ubuntu:14.04 RUN DEBIAN_FRONTEND=noninteractive apt-get update && \ apt-get install -qy \ build-essential ca-certificates curl \ - bzr git mercurial \ + bzr git mercurial openssh-client\ --no-install-recommends ENV GOLANG_VERSION 1.3 From 04164eada3bc89bb3b54aa3dea0f22203ff4aa6e Mon Sep 17 00:00:00 2001 From: Unknwon Date: Sun, 22 Feb 2015 18:24:49 -0500 Subject: [PATCH 29/30] models: able to rename user with diff letter cases #981 - templates/org: mirror fix on name output - routers: add missing error check --- models/org.go | 2 +- models/user.go | 14 +++- routers/org/setting.go | 15 ++-- routers/repo/setting.go | 2 +- routers/user/setting.go | 11 ++- templates/org/base/header.tmpl | 2 +- templates/org/settings/nav.tmpl | 20 ++--- templates/org/settings/options.tmpl | 114 ++++++++++++++-------------- 8 files changed, 97 insertions(+), 83 deletions(-) diff --git a/models/org.go b/models/org.go index 3d37a37d6..b2f9c903a 100644 --- a/models/org.go +++ b/models/org.go @@ -93,7 +93,7 @@ func CreateOrganization(org, owner *User) (*User, error) { return nil, ErrUserNameIllegal } - isExist, err := IsUserExist(org.Name) + isExist, err := IsUserExist(0, org.Name) if err != nil { return nil, err } else if isExist { diff --git a/models/user.go b/models/user.go index 9f9b0cd7f..a974e081f 100644 --- a/models/user.go +++ b/models/user.go @@ -249,11 +249,13 @@ func (u *User) GetFullNameFallback() string { // IsUserExist checks if given user name exist, // the user name should be noncased unique. -func IsUserExist(name string) (bool, error) { +// If uid is presented, then check will rule out that one, +// it is used when update a user name in settings page. +func IsUserExist(uid int64, name string) (bool, error) { if len(name) == 0 { return false, nil } - return x.Get(&User{LowerName: strings.ToLower(name)}) + return x.Where("id!=?", uid).Get(&User{LowerName: strings.ToLower(name)}) } // IsEmailUsed returns true if the e-mail has been used. @@ -278,7 +280,7 @@ func CreateUser(u *User) error { return ErrUserNameIllegal } - isExist, err := IsUserExist(u.Name) + isExist, err := IsUserExist(0, u.Name) if err != nil { return err } else if isExist { @@ -397,6 +399,10 @@ func ChangeUserName(u *User, newUserName string) (err error) { } newUserName = strings.ToLower(newUserName) + if u.LowerName == newUserName { + // User only change letter cases. + return nil + } // Update accesses of user. accesses := make([]Access, 0, 10) @@ -453,7 +459,7 @@ func ChangeUserName(u *User, newUserName string) (err error) { // UpdateUser updates user's information. func UpdateUser(u *User) error { - has, err := x.Where("id!=?", u.Id).And("type=?", INDIVIDUAL).And("email=?", u.Email).Get(new(User)) + has, err := x.Where("id!=?", u.Id).And("type=?", u.Type).And("email=?", u.Email).Get(new(User)) if err != nil { return err } else if has { diff --git a/routers/org/setting.go b/routers/org/setting.go index 41ec4a214..c638a032e 100644 --- a/routers/org/setting.go +++ b/routers/org/setting.go @@ -39,18 +39,18 @@ func SettingsPost(ctx *middleware.Context, form auth.UpdateOrgSettingForm) { // Check if organization name has been changed. if org.Name != form.OrgUserName { - isExist, err := models.IsUserExist(form.OrgUserName) + isExist, err := models.IsUserExist(org.Id, form.OrgUserName) if err != nil { ctx.Handle(500, "IsUserExist", err) return } else if isExist { + ctx.Data["Err_UserName"] = true ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SETTINGS_OPTIONS, &form) return } else if err = models.ChangeUserName(org, form.OrgUserName); err != nil { if err == models.ErrUserNameIllegal { - ctx.Flash.Error(ctx.Tr("form.illegal_username")) - ctx.Redirect(setting.AppSubUrl + "/org/" + org.LowerName + "/settings") - return + ctx.Data["Err_UserName"] = true + ctx.RenderWithErr(ctx.Tr("form.illegal_username"), SETTINGS_OPTIONS, &form) } else { ctx.Handle(500, "ChangeUserName", err) } @@ -68,7 +68,12 @@ func SettingsPost(ctx *middleware.Context, form auth.UpdateOrgSettingForm) { org.Avatar = base.EncodeMd5(form.Avatar) org.AvatarEmail = form.Avatar if err := models.UpdateUser(org); err != nil { - ctx.Handle(500, "UpdateUser", err) + if err == models.ErrEmailAlreadyUsed { + ctx.Data["Err_Email"] = true + ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SETTINGS_OPTIONS, &form) + } else { + ctx.Handle(500, "UpdateUser", err) + } return } log.Trace("Organization setting updated: %s", org.Name) diff --git a/routers/repo/setting.go b/routers/repo/setting.go index 8368513ad..b40ef2d9a 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -109,7 +109,7 @@ func SettingsPost(ctx *middleware.Context, form auth.RepoSettingForm) { } newOwner := ctx.Query("new_owner_name") - isExist, err := models.IsUserExist(newOwner) + isExist, err := models.IsUserExist(0, newOwner) if err != nil { ctx.Handle(500, "IsUserExist", err) return diff --git a/routers/user/setting.go b/routers/user/setting.go index 9398f69a0..a44d3b7e5 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -50,7 +50,7 @@ func SettingsPost(ctx *middleware.Context, form auth.UpdateProfileForm) { // Check if user name has been changed. if ctx.User.Name != form.UserName { - isExist, err := models.IsUserExist(form.UserName) + isExist, err := models.IsUserExist(ctx.User.Id, form.UserName) if err != nil { ctx.Handle(500, "IsUserExist", err) return @@ -58,11 +58,14 @@ func SettingsPost(ctx *middleware.Context, form auth.UpdateProfileForm) { ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SETTINGS_PROFILE, &form) return } else if err = models.ChangeUserName(ctx.User, form.UserName); err != nil { - if err == models.ErrUserNameIllegal { + switch err { + case models.ErrUserNameIllegal: ctx.Flash.Error(ctx.Tr("form.illegal_username")) ctx.Redirect(setting.AppSubUrl + "/user/settings") - return - } else { + case models.ErrEmailAlreadyUsed: + ctx.Flash.Error(ctx.Tr("form.email_been_used")) + ctx.Redirect(setting.AppSubUrl + "/user/settings") + default: ctx.Handle(500, "ChangeUserName", err) } return diff --git a/templates/org/base/header.tmpl b/templates/org/base/header.tmpl index 1bbb092bf..1649b9209 100644 --- a/templates/org/base/header.tmpl +++ b/templates/org/base/header.tmpl @@ -2,7 +2,7 @@
    - {{.Org.FullName}} + {{if .Org.FullName}}{{.Org.FullName}}{{else}}{{.Org.Name}}{{end}}