Что такое bazel linux

Installing Bazel on Ubuntu

Supported Ubuntu Linux platforms:

Bazel will probably work fine on other Ubuntu releases and Debian stretch and above, but we currently do not test this on Bazel’s CI and thus can’t promise it.

Install Bazel on Ubuntu using one of the following methods:

Bazel comes with two completion scripts. After installing Bazel, you can:

Using Bazel’s apt repository

Step 1: Add Bazel distribution URI as a package source

Note: This is a one-time setup step.

The component name “jdk1.8” is kept for legacy reasons only and doesn’t relate to supported or included JDK versions anymore. In the past, when Bazel did not yet bundle a private JRE, we had two release versions, one compatible with JDK 7 and one with JDK 8. However, since we dropped Java 7 support and started bundling a private runtime, Bazel releases are Java version agnostic. Changing the “jdk1.8” component name would break existing users of the repo though.

Step 2: Install and update Bazel

Once installed, you can upgrade to a newer version of Bazel as part of your normal system updates:

The bazel package will always install the latest stable version of Bazel. You can install specific, older versions of Bazel in addition to the latest one like this:

This will install Bazel 1.0.0 as /usr/bin/bazel-1.0.0 on your system. This can be useful if you need a specific version of Bazel to build a project, e.g. because it uses a .bazelversion file to explicitly state with which Bazel version it should be built.

Step 3: Install a JDK (optional)

Bazel includes a private, bundled JRE as its runtime and doesn’t require you to install any specific version of Java.

However, if you want to build Java code using Bazel, you have to install a JDK.

Using the binary installer

While we generally recommend to use the apt repository, the binary installer can be useful in case you don’t have admin permissions on your machine or can’t add custom repositories.

The binary installers can be downloaded from Bazel’s GitHub releases page.

The installer contains the Bazel binary and extracts it into your $HOME/bin folder. Some additional libraries must be installed manually for Bazel to work.

Step 1: Install required packages

Bazel needs a C++ compiler and unzip / zip in order to work:

If you want to build Java code using Bazel, install a JDK:

Step 2: Run the installer

Next, download the Bazel binary installer named bazel- -installer-linux-x86_64.sh from the Bazel releases page on GitHub.

Run it as follows:

The —user flag installs Bazel to the $HOME/bin directory on your system and sets the .bazelrc path to $HOME/.bazelrc . Use the —help command to see additional installation options.

Step 3: Set up your environment

If you ran the Bazel installer with the —user flag as above, the Bazel executable is installed in your $HOME/bin directory. It’s a good idea to add this directory to your default paths, as follows:

Читайте также:  Windows 10 не открывает dvd диски

Источник

Installing Bazel on Ubuntu

This page describes the options for installing Bazel on Ubuntu. It also provides links to the Bazel completion scripts and the binary installer, if needed as a backup option (for example, if you don’t have admin access).

Supported Ubuntu Linux platforms:

Bazel should be compatible with other Ubuntu releases and Debian “stretch” and above, but is untested and not guaranteed to work.

Install Bazel on Ubuntu using one of the following methods:

Note: For Arm-based systems, the APT repository does not contain an arm64 release, and there is no binary installer available. Either use Bazelisk or compile from source.

Bazel comes with two completion scripts. After installing Bazel, you can:

Using Bazel’s apt repository

Step 1: Add Bazel distribution URI as a package source

Note: This is a one-time setup step.

The component name “jdk1.8” is kept only for legacy reasons and doesn’t relate to supported or included JDK versions. Bazel releases are Java-version agnostic. Changing the “jdk1.8” component name would break existing users of the repo.

Step 2: Install and update Bazel

Once installed, you can upgrade to a newer version of Bazel as part of your normal system updates:

The bazel package always installs the latest stable version of Bazel. You can install specific, older versions of Bazel in addition to the latest one, such as this:

This installs Bazel 1.0.0 as /usr/bin/bazel-1.0.0 on your system. This can be useful if you need a specific version of Bazel to build a project, for example because it uses a .bazelversion file to explicitly state with which Bazel version it should be built.

Optionally, you can set bazel to a specific version by creating a symlink:

Step 3: Install a JDK (optional)

Bazel includes a private, bundled JRE as its runtime and doesn’t require you to install any specific version of Java.

However, if you want to build Java code using Bazel, you have to install a JDK.

Using the binary installer

Generally, you should use the apt repository, but the binary installer can be useful if you don’t have admin permissions on your machine or can’t add custom repositories.

The binary installers can be downloaded from Bazel’s GitHub releases page.

The installer contains the Bazel binary and extracts it into your $HOME/bin folder. Some additional libraries must be installed manually for Bazel to work.

Step 1: Install required packages

Bazel needs a C++ compiler and unzip / zip in order to work:

If you want to build Java code using Bazel, install a JDK:

Step 2: Run the installer

Next, download the Bazel binary installer named bazel- -installer-linux-x86_64.sh from the Bazel releases page on GitHub.

Run it as follows:

The —user flag installs Bazel to the $HOME/bin directory on your system and sets the .bazelrc path to $HOME/.bazelrc . Use the —help command to see additional installation options.

Step 3: Set up your environment

If you ran the Bazel installer with the —user flag as above, the Bazel executable is installed in your $HOME/bin directory. It’s a good idea to add this directory to your default paths, as follows:

Источник

Build and test software of any size, quickly and reliably

Why Bazel?

Speed up your builds and tests

Bazel only rebuilds what is necessary. With advanced local and distributed caching, optimized dependency analysis and parallel execution, you get fast and incremental builds.

One tool, multiple languages

Build and test Java, C++, Android, iOS, Go and a wide variety of other language platforms. Bazel runs on Windows, macOS, and Linux.

Scalable

Bazel helps you scale your organization, codebase and Continuous Integration system. It handles codebases of any size, in multiple repositories or a huge monorepo.

Extensible to your needs

Easily add support for new languages and platforms with Bazel’s familiar extension language. Share and re-use language rules written by the growing Bazel community.

Читайте также:  Windows 10 домашняя x64 2020

Trusted by industry leaders

Bazel is the common build tool throughout Pinterest and has been instrumental in achieving fast, reproducible builds across our programming languages and platforms.

Rahul Malik , Software Engineer

Bazel provides a seamless and consistent build interface for different languages in a single system. It increased our productivity significantly. We love it!

Maosong Fu , Engineering Manager

By switching to bazel we not only eliminated the overhead of maintaining multiple build systems, but also massively sped up our build and testing infrastructure.

Michal Witkowski , Principal Tech Lead

When you build software with Bazel, you’re running the same code that has been refined and tested for years at Google to build heavy-duty, mission-critical infrastructure, services, and applications.

Источник

Getting started

This page covers how to start contributing code to Bazel. It covers how to set up your coding environment, describes creating an IntelliJ project and takes you through compiling and debugging your project.

After you set up your environment, there is a quick overview of the structure of Bazel’s code base, how to search and navigate the code, and how to monitor your builds with Bazel’s continuous integration system.

Installing Bazel

Before you start developing, you’ll need to:

Install the latest version of Bazel on your system. For instructions, see Compiling Bazel from source.

Clone Bazel’s Git repository from GitHub:

Install any missing prerequisites.

On Linux/macOS, in Bash/Terminal:

On Windows, in the Command Prompt:

For faster iteration times (but larger binaries), use //src:bazel-dev.exe instead.

This produces a working Bazel binary in bazel-bin/src/bazel (or bazel-bin/src/bazel.exe on Windows).

Creating an IntelliJ project

The IDE that Bazel supports is IntelliJ.

To work with IntelliJ:

  1. Install Bazel’s IntelliJ plug-in.
  2. Set the path to the Bazel binary in the plugin preferences ( Preferences > Other Settings > Bazel Settings ).
  3. Import the Bazel workspace as a Bazel project ( File > Import Bazel Project. ) with the following settings:
    • Use existing Bazel workspace: choose your cloned Git repository.
    • Select Import from workspace and choose the scripts/ij.bazelproject file as the Project view .
  4. Download Google’s Java Code Style Scheme file for IntelliJ, import it (go to Preferences > Editor > Code Style > Java , click Manage , then Import ) and use it when working on Bazel’s code.

Compiling Bazel

You need to compile Bazel in order to test it. To compile a development version of Bazel, you need the latest released version of Bazel, which can be compiled from source.

You can build the Bazel binary using bazel build //src:bazel , using bazel from your PATH. The resulting binary can be found at bazel-bin/src/bazel . This is the recommended way of rebuilding Bazel once you have bootstrapped it.

In addition to the Bazel binary, you might want to build the various tools Bazel uses. They are located in //src/java_tools/. and //src/tools/. and their directories contain README files describing their respective utility.

When modifying Bazel:

  1. Build a distribution archive with bazel build //:bazel-distfile .
  2. Unzip the archive in a new empty directory.
  3. Run bash compile.sh all there.

This command rebuilds Bazel with ./compile.sh , Bazel with compile.sh and Bazel with the Bazel-built binary. It compares if the constructed Bazel builts are identical and then runs all Bazel tests with bazel test //src/. //third_party/ijar/. . This is also used internally to ensure that we don’t break Bazel when pushing new commits.

Debugging Bazel

To create a debug configuration for both C++ and Java in your .bazelrc use:

Rebuild Bazel with bazel build —config debug //src:bazel and use your favorite debugger to start debugging.

To debug the C++ client, run it from gdb or lldb as usual. However, to debug Java code, attach to the server using the following:

  • Run Bazel with the debugging option —host_jvm_debug before the command (e.g., bazel —host_jvm_debug build //src:bazel ).
  • Attach a debugger to the port 5005. For instance, with jdb , run jdb -attach localhost:5005 .
Читайте также:  Убираем размытие windows 10

Our IntelliJ plugin has built-in debugging support.

Using Bazel Continuous Integration

To get started with the Bazel CI system, see Bazel Continuous Integration. To monitor the tests and builds of your Bazel contributions, use the Bazel CI Dashboard.

Bazel’s code description

Bazel has a large codebase with code in multiple locations.

Bazel is organized as follows:

  • Client code is in src/main/cpp and provides the command-line interface.
  • Protocol buffers are in src/main/protobuf .
  • Server code is in src/main/java and src/test/java .
    • Core code which is mostly composed of SkyFrame and some utilities.
    • Built-in rules are in com.google.devtools.build.lib.rules and in com.google.devtools.build.lib.bazel.rules . You might want to read about the Challenges of Writing Rules first.
  • Java native interfaces are in src/main/native .
  • Various tooling for language support are described in the list in the compiling Bazel section.

For a detailed description of the code base, read CODEBASE.md.

Searching Bazel’s source code

To quickly search through Bazel’s source code, use Bazel Code Search. You can navigate Bazel’s repositories, branches, and files. You can also view history, diffs, and blame information. To learn more, see the Bazel Code Search User Guide.

Источник

Google открыла внутреннюю систему сборки — Bazel

  • Поддержка разных языков программирования: Bazel поддерживает Java, Objective-C и C++, а также может быть расширен для поддержки других языков.
  • Высокоуровневый язык конфигурирования сборки: проекты конфигурируются с помощью языка BUILD-файлов, в компактном текстовом формате, который описывает проекты как наборы небольших, взаимосвязанных библиотек, исполняемых файлов и тестов. В отличии от Bazel, Makefile, например, содержат описания конкретных файлов и параметров запуска компилятора.
  • Поддержка множества платформ: один и тот же инструмент используется для сборки ПО для различных архитектур и даже разных платформ. Google использует Bazel для сборки как серверного ПО, так и клиентских приложений на мобильных телефонах.
  • Воспроизводимость результатов: в BUILD файлах каждая библиотека, тест или исполняемый файл прямо указывают свои непосредственные зависимости. Bazel использует эту информацию, чтобы определять, как пересобирать двоичные файлы и параллельно выполнять тесты. Это означает, что все сборки инкрементальны и приводят к одинаковым результатам.
  • Масштабируемость: Bazel легко справляется с большими сборками. В Google достаточно часто серверные приложения занимают 100k строк кода и сборки ветки без отличий от кода основного репозитория могут занимать около 200 мс.
  • Make, Ninja? Эти приложения дают доступ к очень низкоуровневому контролю над выполнением сборки, но пользователь обязан следить за малейшими нюансами и их обеспечивать их правильность. Пользователи взаимодействуют с Bazel на высоком уровне. Примерами правил являются «Javа-тест», «исполняемый файл C++», также существует понятие «целевая платформа». Эти правила показали себя очень удобными на практике и легкими в использовании.
  • Ant и Maven? Ant и Maven в основном используются для Java, в то время как Bazel поддерживает множество языков. Bazel поощряет разделение кодовой базы на мелкие и легко используемые модули и может пересобирать только те модули, которые нуждаются в сборке. Это значительно увеличивает скорость разработки.
  • Gradle? Конфигурационные файлы Bazel значительно более структурированы, позволяя Bazel делать исключительно то, что описывается в тех правилах, которые он поддерживает. Это улучшает параллелизм и повторяемость результатов сборки.
  • Buck, Pants? Обе эти системы сборки были созданы бывшими сотрудниками Google, работающими в Twitter и Facebook. Они были основаны на Bazel, но их функциональность так и не смогла сравниться с оригиналом, потому они никогда не стали возможными альтернативами для самой Google.

Внутри Google используются большие кластеры сборки, они не входят в открытую версию Bazel, которая работает на локальной машине пользователя. В то же время существует поддержка добавления пользовательских удаленных кластеров сборки или кешей двоичных файлов. Такие системы значительно ускоряют сборку двоичных файлов из исходных кодов, которые незначительно отличаются от огромной кодовой базы в основной ветке.

Пример BUILD-файла, который на самом деле является скриптом на Python.

Источник

Оцените статью