Консольный клиент ABF

Материал из Rosalab Wiki
Версия от 12:46, 20 февраля 2014; D uragan (обсуждение | вклад) (Start Russian page)

(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Это снимок страницы. Он включает старые, но не удалённые версии шаблонов и изображений.
Перейти к: навигация, поиск

Введение

Консольный клиент ABF предназначен для поддержки работы с ABF из командной строки и поддерживает наиболее часто выполняемые действия с проектами на - модификацию, сборку и публикацию.

Getting Started

Типичные действия с проектами посредством консольного клиента выполняются следующим образом:

  • Клонирование репозитория проекта
abf get <имя_проекта>

Имя проекта может включать его владельца (в формате <владелец>/<имя_проекта> - например, import/gcc). Если владельца не указывать, то используется значение по умолчанию из настроек клиента.

Эта команда эквивалентна вызову "git clone" со ссылкой на репозиторий проекта.

  • Применить все изменения, сделанные локально в git-репозитории, и отправить их в git-репозиторий на ABF
abf put -m <сообщение>

Эта команда сначала ищет в текущей директории бинарные файлы (например, архивы с исходным кодом), которые упомянуты в spec-файле, и помещает их в файловое хранилище ABF, прописывая соответствующий файлу идентификатор в файл .abf.yml. Затем клиент определяет, какие из файлов, уже присутсвующие в .abf.yml, больше не используются в spec-файле проекта и не нужны при сборке. Такие файлы перемещаются в секцию "removed sources" файла .abf.yml; они не будут загружаться из файлового хранилища при сборке на ABF. После этих дейтсивй, "abf put" запускает последовательность команд "git add --all; git commit -m MSG; "git push".

  1. Запустить сборку
abf build

When called without arguments, this command takes a look at active Git branch, asks ABF about repositories this branch is associated with and initiates a build from the branch to that repositories. You can specify branch to be used and target repositories as additional parameters.

  1. Узнать статус сборки
abf status ID

This command will provide you with a short information about a particular build task. ID of the task is printed to STDOUT by "abf build". You can omit this parameter; in this case status of the last launched project will be checked.

  1. Опубликовать результаты сборки в репозиторий
abf publish ID

If you package has been successfully built, you can publish it to repository. Alternatively, you can specify "--auto-publish" option when invoking "abf build". Note that the latter option will work only if automated publishing is allowed by repository settings and if there is no package with the same name, version and released already published to the target repository.

Пример

Давайте склонируем проект import/gcc project модифицируем его (например, положим новый архив с исходным кодом и обновим spec-файл) и пересоберем пакет.

  • Cклонировать репозиторий проекта и перейти в его папку
 abf get import/gcc -b rosa2012.1
 cd gcc
  • <производим действия по модификации пакета - кладем новый архив с исходным кодом, модифицируем spec-файл и так далее>
  • Загрузить новый архив с исходным кодом в файловое хранилище ABF, прописать ссылку на него в файл .abf.yml и отправить все изменения в git-репозиторий на ABF
abf put -m "Обновленная версия gcc"
 
  • Запустить сборку обновленного проекта на ABF
abf build

(заметьте, что эта команда печатает идентификаторы запущенных задач - они могут вам пригодиться позже, для запроса статуса сборок. Эти идентификаторы также записываются в файл ~/.abf_projects)

  • Узнать статус сборки
    • эта команда выведет статус последней запущенной вами сборки:
abf status
    • а также можно узнать статус сборочных заданий с заданными идентификаторами:
abf status <ID1> <ID2> ...
 
  • Если сборка завершилась успешно, то можно опубликовать ее в репозиторий:
abf publish <ID1> <ID2> ...

Описание команд

Below is the list of all commands officially supported in ABF console client. You can also invoke abf --help and use abf help' command to get descriptions of the commands and actions supported by your version of the client.

help

If you want to get a help for some command, you can launch either abf help <имя_команды> или abf <имя_команды> -h/--help

Запуск и опции:

abf help <имя_команды>

  • <имя_команды>: Имя команды, для которой необходимо вывести справку.

alias

Manage aliases for console client. With aliases you can make your frequently used commands shorter.

For example, you are going to work only with packages for rosa2012.1, you have to checkout to this branch after every "abf get" (or use -b rosa2012.1). But you can just add an alias like "g: get -b rosa2012.1" and after that "abf g" will do it automatically.

Moreover, the alias name can be not only the first abf argument. For example, you can create another useful alias like "pack: rosa2012.1 build_branch -p" and run "abf copy pack" to copy contents of rosa2012.1 branch to build_branch and compress it.

Запуск и опции:

abf alias <action> param1 [param2] [...]

  • <action>: One of actions: list, add, remove.

list

List all the currently available aliases. By default this list looks like

        b: build
       sp: search projects
       su: search users
       st: status
        s: store
      spl: search platforms
       sg: search groups

add

Add a new alias. the first argument is an alias name, all the arguments after that are alias target. For example, abf alias add sg search groups will срфтпу every call of "abf sg rosa" to "abf search groups rosa".

remove

Remove an alias. The only option is an alias name.

clean

Scan the spec and .abf.yml files for possible problems. First, it detects missing sources or patches (which are mentioned in spec using non-remote path, but are absent in current directory and .abf.yml). The check will also fail if there are some problems with the spec file itself and RPM can't parse it. These checks are automatically executed when creating a build task from the current directory. If they fail, the console client refuses to create a build task. This behavior can be turned off by --skip-spec-check option for the build command.

In addition, the 'clean' check reports warnings about files specified in .abf.yml and at the same time in the spec file with remote URL. These warnings are not considered to be crucial and don't prevent the build from being started

get

Clone a remote git repository by its group and name. For example, abf get import/gcc will clone a project gcc from group import.

Запуск и опции:

abf get <имя_проекта> [--branch <branch_name>]

  • <имя_проекта>: a project to clone.
  • -b/--branch <branch_name>: specify a branch to check out inside a cloned git pepository.

Notes:

You can omit a group name, your default group (given from configs) will be used.

put

Upload binary files to File-Store and update (or create) .abf.yml file. Can also commit and push changes.

Запуск и опции:

abf put [--message <message>] [--minimal-file-size <size>] [--do-not-remove-files]

  • -m/--message <message>: With this option specified, "git add --all", "git commit -m <message>" and "git push" will be executed.
  • -s/--minimal-file-size <size>: The minimal file size to upload to File-Store. Smaller files will not be processed. Default is 0B.
  • -n/--do-not-remove-files: By default files are being removed on uploading. Override this behavior.

store

Upload a given file to File-Store. Prints a sha1 hash or error message (with non-zero return code).

If the file with same hash already presents on File-Store, it will not be reuploaded. In any case, file hash will be printed.

Запуск и опции: abf store <path>

  • <path>: A path to file to upload.


fetch

Download all the files listed in .abf.yml from File-Store to local directory.

Запуск и опции:

abf fetch [--only <file_name>]

  • -o/--only <file_name>: Limit the list of downloaded files to this file name(s). This option can be specified more than once.

show

Show some general information about the project. Bash autocomplete uses it. If you are in a git repository directory, command will show information about this project (unless -p/--project specified).

Запуск и опции:

abf show <target> [--project <project_name>]

  • <target>: What has to be displayed. Available choices: build-repos, build-platforms, save-to-repos, save-to-platforms
  • -p/--project <project_name>: Project to show information about. If you are in a git repository, the information for <project_name> will be displayed instead.

Notes:

Repository name includes its platform name. Example of repository name: "rosa2012.1/main" - repository "main" of "rosa2012.1" platform.

Build repository - repository that you can connect to a building chroot.

Target (or save-to) repository - when a build task completed successfully, packages can be published to this repository.

locate

Command to maintain a database of local projects.

Console client tends to maintain a database of local projects: while any interaction with your local git repository via abf-console-client, it stores the path to this repository. After that you can call abfcd [<project_group>/]<project_name> (omit group_name to use your default) to change your current working directory to the project's path (if it had been stored before). If you just want to get a project path without changing directory, use abf locate -p <имя_проекта>.

You can also add projects to this database by manually. To add only one project call abf locate update -d /path/to/project. To scan directory recursively and add all the found projects, call abf locale update-recursive -d /path/to/directory.


Запуск и опции:

abf locate [<action>] [--project <имя_проекта>] [--directory <directory>]

  • <action>: one of {update, update-recursive}. update will update
  • -p/--project <имя_проекта>: Project to show information for (if needed). Format: "[group/]name". If no group specified, your default group will be used.
  • -d/--directory <directory>: Directory to update locations for. It should be a git repository for "update" and any directory for "update-recursive". If not specified - the current directory will be used.


build

Initiate a build task on ABF. There are lots of options, but in most cases it works great with no options at all. abf-console-client tries to automatically resolve all the options needed. How does it work: read notes and examples.


Запуск и опции: abf build [--project <имя_проекта>] [--branch <branch>] [--tag <tag>] [--commit <commit>] [--save-to-repository <repository>] [--repository <repository>] [--arch <arch>] [--auto-publish] [--update-type <type>] [--skip-spec-check]

  • -p/--project <имя_проекта>: project name ([group/]project). If the option is not specified and you are in a git repository directory - a project name will be resolved automatically.
  • -b/--branch <branch>: git branch name to build. Read notes.
  • -t/--tag <tag>: git tag to build. Read notes.
  • -c/--commit <commit>: git commit sha hash to build. Read notes.
  • -s/--save-to-repository <repository>: repository to save results to. If no platform part specified, it is assumed to be "<default_group>_personal". If this option is not specified at all and you are in a git repository, it will be resolved automatically (read notes).
  • -r/--repository <repository>: repositories to build with. Can be set more than once. If no platform part specified, it is assumed to be your "<default_build_platform>". If no repositories were specified at all, it will be resolved automatically (read notes).
  • -a/--arch <arch>: architectures to build for. Can be set more than once. If not set - use all the available architectures for the project given.
  • --auto-publish: Enable automatic publishing.
  • --update-type <type>: Update type, one of {security, bugfix, enhancement, recommended, newpackage}. Default is "security".
  • --skip-spec-check: Do not check spec file.

Notes:

Console client tries to automatically resolve all the options without taking into account anything except --branch. If it fails - use only user-given options. If succeeds, but user specified other parameters - discard everything we've resolved and use only user-given options.

Git hash resolving:

  • Only one of --branch, --tag or --commit options can be used at once.
  • If you've specified commit hash - it will be used "as is".
  • If you've specified branch or tag name - commit hash will be resolved automatically using ABF API. (the hash of top commit in the branch will be used for branch)
  • If you've specified a project name - you have to specify a branch, tag or commit manually.
  • If you've specified no branch, tag or commit hash and you've not specified a project name (you have to be in a git repository) - the top remote commit of your current branch will be used.

Other options resolving:

  • if no --arch specified, use all the available project architectures.
  • build repository can usually be resolved from a git branch name. If there is a build platform with the name of your current git branch exists - it will be used.
  • save-to repository: if some repository from a build platform can be used as save-to repository - it will be used.

You can execute abf build (with no options) when you've specified a branch name (or it's resolved automatically) and there is a platform on ABF having the same name. In this case a save-to repository will be selected from a list of available save-to repositories for this platform. Build repositories are repositories of this platform too("main" and one another repository if needed for selected save-to repository).

Примеры:

  • Build a current branch of a local cloned project. Build and save-to repositories can be resolved from branch name: abf build
  • Build a project without a local git repository. Build and save-to repositories can be resolved from branch name: abf build --project import/gcc --branch rosa2012.1
  • Build a project to another platform: abf build --project import/gcc --branch rosa2012.1 --save-to-repository rosa2012lts/contrib. Build repositories will be rosa2012lts/main and rosa2012lts/contrib.


mock-urpm

Собрать проект локально с использованием mock-urpm. Для сборки используется текущее состояние локального репозитория.

Запуск и опции:

abf mock-urpm [-c <config>]

  • -c/--config <config>: A config template to use. Specify one of the config names from /etc/abf/mock-urpm/configs/. Directory path and extension (".cfg") should be omitted. If no config specified, "default.cfg" will be used. Autocompletion worsk for config names.

Notes:

  • Be careful, "abf fetch" will be called before building a package. It means that if you have modified tarball, but .abf.yml contains a hash of an old one - your tarball will be replaced by downloaded from server.
  • Building root can be found in /var/lib/abf/mock-urpm.

rpmbuild

Собрать проект локально с использованием rpmbuild. Для сборки используется текущее состояние локального репозитория.

Запуск и опции:

abf mock-urpm [-c <config>]

  • -c/--config <config>: A config template to use. Specify one of the config names from /etc/abf/mock-urpm/configs/. Directory path and extension (".cfg") should be omitted. If no config specified, "default.cfg" will be used. Autocompletion worsk for config names.

Notes:

  • Be careful, "abf fetch" will be called before building a package. It means that if you have modified tarball, but .abf.yml contains a hash of an old one - your tarball will be replaced by downloaded from server.
  • Building root can be found in /var/lib/abf/mock-urpm.

publish

Опубликовать успешно завершенное сборочное задание.

Запуск и опции:

abf publish <task_id> [<task_id>] [...]

  • <task_id>: ID of a build list to publish.


copy

Copy files from one git branch to another. Be careful: all the files from destination branch will be removed, and replaced by the files from a source branch.

This command can be useful to keep sources of the project in one branch and build package in another. Just execute abf

Запуск и опции:

  • <src_branch>: A branch to copy files from.
  • <dst_branch>: A branch to copy files to. If not specified, it's assumed to be the current branch.
  • -p/--pack: Create a tar.gz from the <src_branch> and put this archive and spec file to <dst_branch>.

pullrequest

Send a pull request from SRC_BRANCH to DST_BRANCH

Запуск и опции:

abf pullrequest [-h] [-p PROJECT] [-v] from_ref to_ref title body

Positional arguments:

  • <from_ref>: source ref or branch
  • <to_ref>: destination ref or branch
  • <title>: Request title
  • <body>: Request body

Optional arguments:

  • -p PROJECT, --project PROJECT: project name (group/project). By default, the project is used in whose folder this command is launched
-v, --verbose: be verbose, display even debug messages

status

Показать информацию о сборочном задании. It will print something like that:

 Buildlist ID:       944492
 User:               akirilenko
 Project:            import/mock-urpm
 Status:             build has been published
 Build for platform: rosa2012.1
 Save to repository: rosa2012.1/main
 Build repositories: [rosa2012.1/main]
 Architecture:       i586
 Created at:         2013-02-12 15:25:09
 Updated at:         2013-02-12 15:43:16


Запуск и опции:

abf status [--project <имя_проекта>] [--short]

  • -p/--project <имя_проекта>: Project. If last IDs for this project can be found in local database - use them. Otherwise, print error message end exit.
  • -s, --short: Show only one-line information including id, project, arch and status.


clean

Analyze spec file and show missing and unnecessary files from the current git repository directory.

Запуск и опции:

abf clean [--auto-remove]

  • -a/--auto-remove: автоматически удалять все ненужные файлы.

search

Поиск по ABF.

Запуск и опции:

abf search <target> "<query>"

  • <target>: область поиска; допустимые значения:
    • users - пользователи
    • groups - группы
    • platforms - платформы
    • projects -проекты
  • <query>: Строка для поиска. Регулярные выражения и шаблоны не поддерживаются.

test

Запустить набор внутренних тестов.

Эта команда может быть использована для проверки исправности консольного клиента и окружения. В штатном режиме работы, тесты не должны выявлять никаких проблем и должны печатать результирующую фразу "Datamodel seems to work fine".

Дополнительные возможности

Кэш локального местоположения проектов

Консольный клиент ABF запоминает метоположение в файловой системе всех репозиториев, склонированных с его помощью. За счет этого, вы можете быстро перемещаться между склонированными проектами с помощью команды "abfcd":

abfcd <имя_проекта>

Эта информация хранится в файле .abf_projects в вашей домашней директории.

Узнать местоположение проекта в вашей файловой системе можно с помощью следующей команды:

abf locate -p <имя_проекта>

Если у вас есть набор репозиториев, отсутствующих в кэше консольного клиента (например, если они были склонированы непосредственно с помощью команды git, или если вы удалили файл .abf_projects), вы можете заставить консольного клиента просканировать заданную директорию и поместить в кэш все проекты, которые он там найдет:

abf locate update-recursive -d <путь_к_директории_с_проектами>

Помимо команды "abfcd", информация из файла .abf_projects используется при перемещении файлов между различными проектами с помощью консольного клиента ABF.

Автодополнение в Bash

Консольный клиент ABF предоставляет богатые возможности по автоматическому дополнению команд и опций при использовании в оболочке Bash. В частности, он способен предлагать варианты дополнения для имен опций, веток git, целевых репозиториев для сборки (параметров build и save-to команды "abf build") и множества других команд. Это существенно облегчает работу с клиентом, поскольку отпадает необходимость в ручном вводе длинных имен и запоминании большого количества опций. В некоторых случаях автоматическое дополнение может работать более 1 секунды, однако все результаты обращения к автоматическому дополнению кэшируются и последующие вызовы проходят гораздо быстрее.