Bitbucket для повышения качества кода. Четыре шага, чтобы начать работу
Прежде чем начать, вам понадобится аккаунт Bitbucket Cloud, чтобы повторять действия, описанные в этом обучающем руководстве. Из этого руководства вы узнаете о компонентах Bitbucket, которыми будете часто пользоваться, поэтому у вас также должна быть установлена система Git и вы должны быть знакомы с ее основными командами и принципами работы.
Теперь можно загрузить код в Bitbucket.
Шаг 1. Переместите свой код в Bitbucket
Репозитории (которые специалисты с любовью называют «репами») — это место, где код хранится в Bitbucket. Начать работу можно по-разному в зависимости от ваших потребностей.
- С чистого листа
- При помощи другого поставщика
Создание нового пустого репозитория
- Нажмите + на общей боковой панели, расположенной в левой части экрана, и выберите в разделе Create new (Создать) пункт Repository (Репозиторий).
- Присвойте репозиторию имя. Это важно! Имя репозитория включается в его URL-адрес.
- Выберите для параметра Include a README? (Добавить файл README?) значение Yes, with a template (Да, с помощью шаблона).
- Настройки остальных параметров можно не менять. Нажмите Create (Создать).

Импорт репозитория от другого поставщика Git
-
Нажмите + на общей боковой панели, расположенной в левой части экрана, и выберите в разделе Import (Импорт) пункт Repository (Репозиторий).
Укажите URL для доступа к репозиторию.
Если для доступа к вашему репозиторию требуется авторизация, установите флажок Requires authorization (Требуется авторизация) и введите учетные данные для доступа.
Присвойте репозиторию имя. Это важно! Имя репозитория включается в его URL-адрес.
Настройки остальных параметров можно не менять. Нажмите Import repository (Импортировать репозиторий).

Шаг 2. Подготовьте локальную систему, чтобы сотрудничать с коллегами со всего мира
Теперь, когда у вас есть репозиторий в облаке, нужно подготовить локальную систему, с помощью которой вы будете писать или изменять код в Bitbucket. К этому моменту у вас должна быть установлена и настроена система Git. Если вы пропустили этот шаг, вернитесь и выполните необходимые действия. Напоминаем, что у нас есть для этого отдельное руководство!
Клонирование репозитория Bitbucket
Итак, вы создали (или импортировали) репозиторий. Прежде чем вы сможете принять участие в изменении кода в репозитории Bitbucket, вы должны клонировать этот репозиторий в свою локальную систему. Подробнее о клонировании в Git.
- Нажмите «+» на общей боковой панели, расположенной в левой части экрана, и выберите в разделе Get to work (Приступаем к работе) пункт Clone this repository (Клонировать этот репозиторий).
- Выберите в меню, расположенном в правом верхнем углу экрана, вариант HTTPS (если вы уже не настроили SSH-ключи).
- Скопируйте команду клонирования.

Из интерфейса командной строки
- Перейдите в каталог, в который вы хотите клонировать репозиторий. cd
- Вставьте команду, которую вы скопировали из Bitbucket (она будет выглядеть примерно так): git clone https://username@bitbucket.org/teamsinspace/documentation-test.git
На вашем локальном диске появится новый подкаталог с тем же именем, что и клонированный репозиторий. Если вы клонировали пустой репозиторий, этот локальный каталог пока может быть пуст.
Изменение файла в Bitbucket в режиме онлайн
Подождите, у меня нет файлов в Bitbucket.
Вы пропустили необязательный шаг и не добавили файл README в репозиторий Bitbucket? Не переживайте! Если репозиторий пуст, перейдите в него и нажмите Create a README (Создать файл README). Теперь вы можете клонировать репозиторий, в котором есть файлы.
Извлечение (pull) обновлений из Bitbucket
Из интерфейса командной строки
- Перейдите в каталог, в который вы хотите клонировать репозиторий. cd
- Вставьте команду, которую вы скопировали из Bitbucket (она будет выглядеть примерно так): git clone
Выполнив команду, вы загрузите все изменения, внесенные в эти файлы, в свою локальную систему.
Шаг 3. Выполняйте базовые операции с ветками с помощью Bitbucket
Благодаря ветвлению участники команды могут работать одновременно над разными участками кода, не изменяя исходную базу кода и не мешая работе других участников. Когда вы будете готовы выполнить слияние изменений, отправьте свою ветку в Bitbucket, чтобы ее можно было проверить посредством запроса pull.
Создавать ветки можно несколькими способами. Выберите тот, который лучше других отвечает потребностям вашей команды.
Создание ветки
- Из Bitbucket (самый простой способ)
- Из интерфейса командной строки
- Из Jira
- Находясь в репозитории, нажмите «+» на общей боковой панели и выберите в разделе Get to work (Приступаем к работе) пункт Create a branch (Создать ветку).
- В появившемся всплывающем окне выберите Type (Тип) (если вы используете модель ветвления), введите имя ветки в поле Branch name (Имя ветки) и нажмите Create (Создать).

Из интерфейса командной строки
- После создания ветки выберите ее и переключитесь на эту ветку в вашей локальной системе. Bitbucket автоматически отобразит необходимую команду, которая будет выглядеть примерно так: git fetch && git checkout
- Внесите изменения в локальной системе, затем добавьте изменения, сделайте коммит и отправьте изменения в ветку: git add . git commit -m «добавлено изменение в функциональную ветку» git push origin
- Перейдите на страницу Source (Исходный код) в своем репозитории. В раскрывающемся списке вы увидите главную ветку и ветку

Из интерфейса командной строки, находясь в каталоге локального репозитория
- Создайте ветку с помощью команды Git branch. git branch
- Просмотрите список веток в репозитории. Вы увидите главную ветку по умолчанию и новую ветку, которую вы создали. git branch
Переключитесь на эту ветку. git checkout
Отправьте новую ветку в Bitbucket. git push —set-upstream origin
Теперь перейдем в Bitbucket и посмотрим на нашу ветку.
Перейдите в репозиторий.
Нажмите Branches (Ветки).

Для этого у вас должен быть доступ к сервису Jira Software Cloud, который вы должны интегрировать с Bitbucket. Для этого нужны права администратора, но если вы хотите просто поэкспериментировать с интеграцией и посмотреть, как она работает, вы всегда можете оформить подписку на бесплатную пробную версию Jira Software Cloud.
Интеграцию этих двух продуктов можно выполнить сразу после настройки сайта Jira. Инструкции по интеграции приведены в статье Подключение Bitbucket Cloud к Jira Software Cloud.
Шаг 4. Проверьте изменения кода при помощи запроса pull
Когда изменения вашего кода переданы в Bitbucket, они должны быть проверены коллегой. Запросить проверку кода и в целом вести совместную работу в общей среде со своей командой проще и эффективнее всего посредством запросов pull.
Создание запроса pull
- В открытом репозитории нажмите «+» на общей боковой панели и выберите в разделе Get to work (Приступаем к работе) пункт Create a pull request (Создать запрос pull).
- Заполните остальные поля формы запроса pull:

- Source (Источник): репозиторий и ветка, в которой вы изменили код и теперь хотите выполнить слияние этих изменений.
- Destination (Назначение): репозиторий и ветка, в которую вы хотите слить изменения.
- Title and Description (Заголовок и описание): значения этих двух полей будут использоваться в уведомлениях, отправляемых по электронной почте. Заголовок также будет отображаться в списке запросов pull.
- Reviewers (Проверяющие): выберите проверяющих, которые будут оставлять полезные отзывы об изменениях и должны будут подтверждать изменения.
- Close branch (Закрыть ветку): установите этот флажок, если хотите, чтобы ветка автоматически закрылась после слияния запроса pull.
- Diff and Commits (Различия и коммиты): на этих вкладках можно просмотреть внесенные изменения (Diff) и включенные коммиты.
- Нажмите Create pull request (Создать запрос pull).
Этот запрос pull появится в списках запросов pull на боковой панели навигации вашего репозитория.
Проверка запроса pull
Если вас выбрали в качестве проверяющего, вы получите уведомление о том, что запрос pull ожидает вашей проверки. Кроме того, открытые запросы pull можно просмотреть на вкладке Pull requests (Запросы pull) на дашбоарде. Проверку кода в целях обеспечения качества можно выполнить разными способами — выбор за вами. Ниже описано несколько способов того, как можно поддерживать эффективную связь с коллегами, чтобы все понимали, что именно было изменено, и были согласны с изменением, подготовленным к слиянию.
Просмотр различий
Если просмотреть запрос pull, вы увидите различия (изменения) во всех файлах, измененных в запросе pull. Добавленные строки выделяются зеленым цветом, удаленные — красным. Также можно нажать на вкладке Commits (Коммиты) в верхней части запроса pull, чтобы просмотреть, какие коммиты включены. Это удобно при проверке больших запросов pull.
Отзывы и вопросы в комментариях
В Bitbucket можно оставлять комментарии ко всему запросу pull, отдельному файлу или отдельному участку кода в файле. Благодаря этому можно легко поместить отзыв в контекст или конкретизировать его. Комментарии можно сопровождать изображениями, ссылками, форматированным текстом. Каждый комментарий имеет собственный URL-адрес, чтобы им можно было быстро поделиться.
Подтверждение или отклонение запроса pull
Выполнив проверку изменений кода, вы должны сообщить автору запроса pull, готов ли запрос к слиянию. Нажмите кнопку Approve (Подтвердить), чтобы автор запроса получил уведомление о том, что вы считаете слияние изменений возможным. Если вы нажмете кнопку Decline (Отклонить), автор запроса получит противоположное по смыслу уведомление. Отклоненный запрос pull нельзя будет открыть снова. Чтобы выполнить слияние ветки, нужно будет открыть новый запрос pull.
Учтите, что отклонение запроса pull может плохо сказаться на моральном духе автора, поэтому к нему следует прибегать, только если изменения совсем не годятся или данная работа уже не требуется. Сохраняйте доброжелательность, проверяя чужую работу, и всегда стремитесь в первую очередь понять и уже потом — быть понятым.

Слияние запроса pull
После того как код прошел проверку и был подтвержден в рамках запроса pull, нажмите кнопку Merge (Слияние), чтобы выполнить слияние вашей ветки с основной. Изменения кода из исходной ветки будут полностью включены в целевую ветку.
BitBucket — download source as ZIP
I know I can get the project through git clone command, but is there any way, how to download the project through the web interface from BitBucket.org? In the best way, I am looking for a way to download a project source as ZIP compress file.
8 Answers 8
For the latest version of Bitbucket (2016+), the download link can be found in the Download menu item.

First method
In the Overview page of the repo, there is a link to download the project.

Second method
Go to Downloads -> Branches -> Download the branch that you want (as .zip, .gz or .bz2). There you’ll find download links for all tags. The links will be in the format:
By tweaking it a little bit, you can also have access to any revision by changing the tag to the commit hash:
Now Its Updated and very easy to download!
Select your repository from Dashboard or Repository tab.
And then just click on Download tab having icon of download. It will Let you download whole repository in zip format.

For git repositories, to download the latest commit, you can use:
For mercurial repositories:
![]()
In Bitbucket Server you can do a download by clicking on . next to the branch and then Download

![]()
Direct download:
Go to the project repository from the dashboard of bitbucket. Select downloads from the left menu. Choose Download repository.

![]()
To Download Specific Branch — Go To Downloads from Left panel, Select Branches on Downloads page. It will list all Branches available. Download your desired branch in zip, gz, or bz2 format.

![]()
I was trying to figure out if it’s possible to browse the code of an earlier commit like you can on GitHub and it brought me here. I used the information I found here, and after fiddling around with the urls, I actually found a way to browse code of old commits as well. Even though the question/answer is about downloading the code of an earlier commit, I thought I’d just add an answer for browsing the code also.
When you’re browsing your code the URL is something like:
and by adding a commit hash at the end like this:
You can browse the code at the point of that commit. I don’t understand why there’s no dropdown box for choosing a commit directly, the feature is already there. Strange.
Three Ways to Back Up a Single File from Bitbucket

Ever spent time trying to problem-solve only to suddenly recall that you’ve solved a similar problem in the past? You go looking for the project that has the solution in your Bitbucket, find it, and realize the solution consists of about three files.
You don’t want to download the entire repository, it’s huge. How do you download only those three files without cloning the entire repository?
From experimental purposes to debugging to reusing the same file in a new project, there are many different reasons you might want to download individual files from Bitbucket. So let’s go over three ways you can download files directly from Bitbucket without having to clone the entire repository.
1. Manual Download From Your Browser
This is the easiest way to download files from your Bitbucket repository. You don’t have to write any commands—it’s a simple visual process. You only need to navigate to the right repository, look for the files, and download them one after the other.
Here’s a walk-through for manually backing up a file on Bitbucket:
- Log in to your Bitbucket account.
- Search for the repository where your target file is and click on it.
3. Click the ellipsis menu at the top right of the file window to receive a drop-down. Right-click Open raw and save the file with its file type using your browser’s Save Link As feature.

Advantages of Downloading Single Files Manually
It’s a simple method. You just need to follow a few steps and click the right buttons, as described above.
Disadvantages of Downloading Single Files Manually
If you have to automate your processes, this will likely not be the option for you. It doesn’t make sense to add files one after the other manually to your development/deployment pipeline. It’s better off automated with a script. And if you have to do this for a lot of files, it’ll take a lot of time and monitoring.
2. curl
We can make this process faster with curl, a command-line tool that allows you to transfer data using one of the supported protocols: HTTP, DICT, FILE, GOPHER, HTTPS, IMAP, IMAPS, FTP, FTPS, or LDAP.
For this article, let’s use the HTTPS transfer protocol to download files from Bitbucket since HTTPS is enabled on the Bitbucket domain. If it’s a private repository, you’ll be required to log in to access the files anyway, so log in with curl and set the repository, branch, and the filename of the file you’re looking to download on your terminal as shown below:
We use the flag —user to specify user authentication credentials. This might not be necessary if your repository is public. Also, we use the -o (output) to specify the name of the output file.
Advantages of Downloading with curl
You’ll benefit from the curl method if you’re a command-line person. It’s easy and fast—you’ll only need to replace a few parameters in the code and hit Enter on your command line. Bonus, curl comes preinstalled on Windows, Linux, and macOS.
Occasionally, you may need a file from another repository that’s continuously updated to make your own script work properly. In that case, this method can be a great way to download the script and add it to your workflow without having to do it manually.
Here’s a simple Node.js example of a script that automatically runs curl to download a file from your Bitbucket account using Child Process in Node.js:
«`javascript
const cp = require(‘child_process’);
let download = async function(uri, filename, username, password) <
let command = `curl —user $
let result = cp.execSync(command);
>;
(async function test() <
await download(‘https://bitbucket.org/ezesundayeze/jobdispatcher/raw/HEAD/jobdispatcher/manage.py’, ‘manage.py’, «username», «password»)
>)()
Disadvantages of Downloading with curl
Even as a one-liner, some devs will prefer a more visual process. In that case, you might prefer the manual process discussed in section 1.
3. WGET
Wget is a command-line utility like curl that allows you to retrieve data from a remote server. Some differences between the two are beyond the scope of this article, however, it’s important to know that it can do the job in as much as curl can and in an even shorter way.
You only need to specify the path to the file and enter the username and password with the flag —ask-password to request the user to enter their password when they execute the command. You can also use —password to enter the password directly from the command line without being asked.
You’ll also need to pass — user to the command as shown in the code below. But if your repository is public, you won’t need the username and password arguments.
wget —user
Advantages of Using Wget
It’s fast and easy to use and can be integrated into your codebase easily with libraries such as node-wget, wget-improved, and Java-wget. It also requires fewer arguments as compared to curl.
Disadvantages of Using Wget
Wget does not come pre-installed with Windows, Linux, or macOS. You’ll have to install it manually.
Conclusion
So we’ve covered three ways to download single files from a Bitbucket repository. From the manual process to using curl and Wget, you should have a solid idea of the advantages and disadvantages of each and whether or not they can make your work easier.
I feel like Bitbucket could have made this process a lot easier if they had introduced a simple API to allow developers to download individual files from any repository. But developers will always find new ways to solve challenges as they come up.
Rewind supports full repository backups for Bitbucket. To start backing up your Bitbucket repositories, you can find us in the Atlassian Marketplace.
Build it vs. Buy it cost comparison
Use this tool to compare the cost of building your own backup solution versus leveraging one such as Rewind.
Download a repository archive
With Bitbucket Data Center and Server you can download an archive of source files at a particular point in time; you can download your source as a .zip file from the actions dropdown menu from the Source view, Commits list, and Branches list. You can also download the archive of individual branches, commits, and tags.
To download a single file, navigate to the file in the repository, select Raw file and save the file that opens up in your browser.
On this page:
What’s the difference between downloading and cloning a repository?
Cloning a repository copies the source files of a remote repository to your local machine, as well as the repository’s Git history (branches, commits, tags, etc.). Cloning also creates a remote connection (usually called origin) pointing back to the cloned repository. You can only clone into a local directory that is a properly initialized Git repository (using the git init command).
Downloading a repository archive only copies a repository’s source files from a specific point in time, depending on what was chosen to be copied. The biggest difference to downloading an archive is that you are not copying the repository history, or creating a connection to the remote repository. You are only getting the source files, and none of the Git metadata stored in the .git directory.
Download your source as a .zip file
To download a repository archive of a branch:
- Go to either the Source view, Commit view, or Branches list of a repository.
- Using the branch selector to choose a branch.
- Click the actions dropdown next to the branch selector, then select Download.

You can also download a repository archive of a specific branch in the actions menu of any branch, as viewed from the Branches list.

To download a repository archive from a commit:
- Click on the hash number of a commit to view a single commit.
- Click Download this commit in the upper-right panel.

To download a repository archive from a tag:
- Go to either the Source view, Commit view, or Branches list of a repository.
- Using the branch selector to choose a tag.
- Click the actions dropdown next to the branch selector, then select Download.


Download your source as a .tar or .tar.gz file
When you download your source file from Bitbucket’s UI, you are downloading the file in .zip format. However, it is possible to edit the URL and get the archive as other formats, like .tar, .gz, or .tar.gz.
To download your source as a file format other than .zip:
- Follow any of the instructions listed above, so that you are viewing the source you want to download.
- Right-click the Download link and copy the URL address.
Paste the URL in the browser, it would look something like this:
Change format=zip to the format of your choice.
For .tar.gz files, change the argument to format= tgz .
For .tar files, change the argument to format= tar .