Эта страница была обновлена 2022-01.

Для начала прочтите руководство нового разработчика.

Базовые принципы и стиль форматирования кода

Большинство из нижеследующего должно быть хорошо известно каждому, кто участвует в разработке open source или в коммерческой среде разработки. Нижеследующее применимо к большей части основной разработки ветки i2p.i2p. Руководства для других веток, дополнений и внешних приложений могут существенно отличаться; для уточнения свяжитесь с соответствующим разработчиком.

Общество

  • Please don't just "write code". If you can, participate in other development activities, including: development discussions and support on IRC, i2pforum.i2p; testing; bug reporting and responses; documentation; code reviews; etc.
  • Активные разработчики должны периодически быть доступны по IRC #i2p-dev. Будьте в курсе текущего цикла выпуска. Придерживайтесь релизных вех, таких как freeze, tag freeze и checkin deadline для релиза.

Релизный цикл

The normal release cycle is 6-12 weeks. Following are the approximate deadlines within a typical 8-week cycle. Actual deadlines for each release are set by the release manager after consultation with the full team.

  • 1-2 дня после предыдущего релиза: Чекины в trunk разрешены.
  • 2-3 недели после предыдущего релиза: Deadline на перенос основных изменений из других веток в trunk.
  • 4-5 недель до релиза: Deadline для запросов новых ссылок домашних страниц.
  • 3-4 недели до релиза: Заморозка возможностей. Deadline для основных новых возможностей.
  • 2-3 недели до релиза: Проводите встречу для просмотра новых запросов ссылок домашних страниц, если есть.
  • 10-14 days before release: String freeze. No more changes to translated ("tagged") strings. Push strings to Transifex, announce translation deadline on Transifex.
  • 10-14 days before release: Feature deadline. Bug fixes only after this time. No more features, refactoring or cleanup.
  • 3-4 days before release: Translation deadline. Pull translations from Transifex and check in.
  • 3-4 days before release: Checkin deadline. No checkins after this time without the permission of the release builder.
  • Часы до релиза: deadline просматривания кода

Git

  • Have a basic understanding of distributed source control systems, even if you haven't used git before. Ask for help if you need it. Once pushed, checkins are forever, there is no undo. Please be careful. If you have not used git before, start with baby steps. Check in some small changes and see how it goes.
  • Test your changes before checking them in. If you prefer the checkin-before-test development model, use your own development branch and propagate back to i2p.i2p once it is working well. Do not break the build. Do not cause regressions. In case you do (it happens), please do not vanish for a long period after you push your change.
  • Если ваши изменения нетривиальны, или вы хотите чтобы люди их протестировали, и вам нужны хорошие отчеты о тестировании, дабы знать, протестированы ваши изменения или нет - добавьте чекин-комментарий в history.txt и увеличьте версию сборки в RouterVersion.java.
  • Ensure that you 'git pull' to the latest revision before you check in and push. If you inadvertently diverge, merge and push as soon as possible. Don't routinely make others merge for you.
  • Do not check in major changes into the main i2p.i2p branch late in the release cycle. If a project will take you more than a couple days, create your own branch in git and do the development there so you do not block releases.

Стиль форматирования кода

  • В большинстве кода для отступа используется 4 пробела. Не используйте символ табуляции. Не переформатируйте код. Если ваш IDE или редактор хочет отформатировать все, возьмите его под контроль. Да, мы знаем, что 4 пробела это та еще головная боль, но, возможно, вы сможете правильно настроить свой редактор. В некоторых местах стиль форматирования может разниться. Руководствуйтесь здравым смыслом. Воспроизводите имеющийся стиль в файле, который вы изменяете.
  • Все новые классы и методы с модификатором public и package-private требуют Javadocs. Добавьте @since номер_релиза. Javadocs очень желателен для новых методов с модификатором private.
  • For any Javadocs added, there must not be any doclint errors or warnings. Run 'ant javadoc' with Oracle Java 14 or higher to check. All params must have @param lines, all non-void methods must have @return lines, all exceptions declared thrown must have @throws lines, and no HTML errors.
  • Классы в core/ (i2p.jar) и куски i2ptunnel - это части нашего официального API. Есть несколько out-of-tree плагинов и других приложений, которые основаны на этом API. Будьте осторожны при их изменении, чтобы не поломать совместимость. Добавляйте методы в API, только если они полезны для всех. Javadocs для методов API должны быть просты и полны. Если вы вносите изменения в API, обновите также документацию на веб-сайте (i2p.www branch).
  • Tag strings for translation where appropriate, which is true for all UI strings. Don't change existing tagged strings unless really necessary, as it will break existing translations. Do not add or change tagged strings after the "tag freeze" in the release cycle so that translators have a chance to update before the release.
  • По возможности используйте дженерики и конкурентные классы. I2P - это сильно мульти-потоковое приложение.
  • Ознакомьтесь с распространенными "подводными камнями" в Java, которые найдены findbugs. Выполните 'ant findbugs', чтобы узнать больше.
  • Java 8 is required to build and run I2P as of release 0.9.47. Do not use Java 7 or 8 classes or methods in embedded subsystems: addressbook, core, i2ptunnel.jar (non-UI), mstreaming, router, routerconsole (news only), streaming. These subsystems are used by Android and embedded applications that require only Java 6. All classes must be available in Android API 14. Java 7 language features are acceptable in these subsystems if supported by the current version of the Android SDK and they compile to Java 6-compatible code.
  • Try-with-resources cannot be used in embedded subsystems as it requires java.lang.AutoCloseable in the runtime, and this is not available until Android API 19 (KitKat 4.4).
  • The java.nio.file package cannot be used in embedded subsystems as it is not available until Android API 26 (Oreo 8).
  • Other than the above limitations, Java 8 classes, methods, and constructs may be used in the following subsystems only: BOB, desktopgui, i2psnark, i2ptunnel.war (UI), jetty-i2p.jar, jsonrpc, routerconsole (except news), SAM, susidns, susimail, systray.
  • Plugin authors may require any minimum Java version via the plugin.config file.
  • Выполняйте явное преобразование примитивных классов и типов; не полагайтесь на autoboxing/unboxing.
  • Не используйте URL. Используйте URI.
  • Не ловите Exception. Поймайте RuntimeException и проверьте исключения индивидуально.
  • Не используйте String.getBytes() без указания аргумента в значении UTF-8. Вы также можете использовать DataHelper.getUTF8() или DataHelper.getASCII().
  • Всегда указывайте кодировку UTF-8, когда считываете или записываете файлы. Утилиты DataHelper также могут быть полезны.
  • Always specify a locale (for example Locale.US) when using String.toLowerCase() or String.toUpperCase(). Do not use String.equalsIgnoreCase(), as a locale cannot be specified.
  • Не используйте String.split(). Используйте DataHelper.split().
  • Don't add code to format dates and times. Use DataHelper.formatDate() and formatTime().
  • Убедитесь, что InputStream и OutputStream заключены в блоки finally.
  • Используйте { } для всех блоков for и while, даже если это всего одна строка. Если вы используете { } для блоков if, else или if-else, то используйте их для всех блоков. Ставьте "} else {" на одной строке.
  • Задавайте fields как final когда только возможно.
  • Don't store I2PAppContext, RouterContext, Log, or any other references to router or context items in static fields.
  • Don't start threads in constructors. Use I2PAppThread instead of Thread.

Logging

The following guidelines apply to the router, webapps, and all plugins.
  • For any messages not displayed at the default log level (WARN, INFO, and DEBUG), unless the message is a static string (no concatenation), always use log.shouldWarn(), log.shouldInfo(), or log.shouldDebug() before the log call to avoid unnecessary Object churn.
  • Log messages that may be displayed at the default log level (ERROR, CRIT, and logAlways()) should be brief, clear, and understandable to a non-technical user. This includes exception reason text that may also be displayed. Consider translating if the error is likely to happen (for example, on form submission errors). Otherwise, translation is not necessary, but it may be helpful to search for and reuse a string that is already tagged for translation elsewhere.
  • Log messages not displayed at the default log level (WARN, INFO, and DEBUG) are intended for developer use, and do not have the above requirements. However, WARN messages are available in the Android log tab, and may be of assistance to users debugging issues, so use some care with WARN messages as well.
  • INFO and DEBUG log messages should be used sparingly, especially in hot code paths. While useful during development, consider removing them or commenting them out after testing is complete.
  • Do not log to stdout or stderr (wrapper log).

Лицензии

  • Only check in code that you wrote yourself. Before checking in any code or library jars from other sources, justify why it is necessary, verify the license is compatible, and obtain approval from the release manager.
  • If you do obtain approval to add external code or jars, and binaries are available in any Debian or Ubuntu package, you must implement build and packaging options to use the external package instead. Checklist of files to modify: build.properties, build.xml, debian/control, debian/i2p-router.install, debian/i2p-router.links, debian/rules, sub-build.xml
  • Для любых image, зачекиненных из внешних источников, вашей ответственностью является проверка совместимости лицензии. Включите лицензию и информацию об источнике в комментарий к чекину.

Ошибки

  • Managing issues are everybody's job, please help. Monitor for issues you can help with. Comment on, fix, and close issues if you can.
  • New developers should start by fixing issues. When you have a fix, attach your patch to the issue and add the keyword 'review-needed'. Do not close the issue until it's been successfully reviewed and you've checked your changes in. Once you've done this smoothly for a couple of tickets, you may follow the normal procedure below.
  • Close an issue when you think you've fixed it. We don't have a test department to verify and close tickets. If you arent sure you fixed it, close it and add a note saying "I think I fixed it, please test and reopen if it's still broken". Add a comment with the dev build number or revision and set the milestone to the next release.