Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 65 additions & 64 deletions book/B-embedding-git/sections/jgit.asc
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
=== JGit

(((jgit)))(((java)))
If you want to use Git from within a Java program, there is a fully featured Git library called JGit.
JGit is a relatively full-featured implementation of Git written natively in Java, and is widely used in the Java community.
The JGit project is under the Eclipse umbrella, and its home can be found at http://www.eclipse.org/jgit[].
Якщо ви бажаєте використовувати Git з Java програми, існує повнофункціональна бібліотека Git під назвою JGit.
JGit -- це відносно повнофункціональна імплементація Git, написана на Java, та широко використовується в спільноті Java.
Проект JGit знаходиться під опікою Eclipse, та його домашню сторінку можна знайти за адресою http://www.eclipse.org/jgit[].

==== Getting Set Up
==== Налаштовуємо

There are a number of ways to connect your project with JGit and start writing code against it.
Probably the easiest is to use Maven – the integration is accomplished by adding the following snippet to the `<dependencies>` tag in your pom.xml file:
Є декілька способів додати JGit до вашого проекту та розпочати писати код з його використанням.
Напевно найлегшим є Maven – інтеграцію можна зробити, додавши наступний код до теґу `<dependencies>` у вашому файлі pom.xml:

[source,xml]
----
Expand All @@ -19,116 +19,117 @@ Probably the easiest is to use Maven – the integration is accomplished by addi
</dependency>
----

The `version` will most likely have advanced by the time you read this; check http://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit[] for updated repository information.
Once this step is done, Maven will automatically acquire and use the JGit libraries that you'll need.
`version` напевно збільшиться, коли ви будете це читати; дивіться http://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit[] для оновленої інформації про репозиторій.
Щойно це зроблено, Maven автоматично отримає та використає бібліотеки JGit, які вам потрібні.

If you would rather manage the binary dependencies yourself, pre-built JGit binaries are available from http://www.eclipse.org/jgit/download[].
You can build them into your project by running a command like this:
Якщо ви бажаєте власноруч контролювати двійкові залежності, то зібрані двійкові файли JGit доступні вам за адресою http://www.eclipse.org/jgit/download[].
Ви можете вбудувати їх до свого проекту, якщо виконаєте таку команду:

[source,console]
----
javac -cp .:org.eclipse.jgit-3.5.0.201409260305-r.jar App.java
java -cp .:org.eclipse.jgit-3.5.0.201409260305-r.jar App
----

==== Plumbing
==== Кухонне

JGit has two basic levels of API: plumbing and porcelain.
The terminology for these comes from Git itself, and JGit is divided into roughly the same kinds of areas: porcelain APIs are a friendly front-end for common user-level actions (the sorts of things a normal user would use the Git command-line tool for), while the plumbing APIs are for interacting with low-level repository objects directly.
JGit має два рівні API: кухонний (plumbing -- дослівно водопровід) та парадний (porcelain -- дослівно порцеляна).
Ця термінологія походить зі самого Git, та JGit розділено на приблизно такі самі частини: парадне API -- зручний інтерфейс для поширених дій рівня користувача (такі речі, для яких звичайний користувач Git використовує інструмент командного рядку), в той час як кухонне API призначено для взаємодії з низькорівневими обʼєктами сховища напряму.

The starting point for most JGit sessions is the `Repository` class, and the first thing you'll want to do is create an instance of it.
For a filesystem-based repository (yes, JGit allows for other storage models), this is accomplished using `FileRepositoryBuilder`:
Більшість сесій JGit починаються з класу `Repository`, та перше, що ви бажаєте зробити -- створити його примірник (instance).
Для сховищ заснованих на файлових системах (так, JGit дозволяє інші моделі збереження), це досягається за допомогою `FileRepositoryBuilder`:

[source,java]
----
// Create a new repository
// Створення нового репозиторію
Repository newlyCreatedRepo = FileRepositoryBuilder.create(
new File("/tmp/new_repo/.git"));
newlyCreatedRepo.create();

// Open an existing repository
// Відкриття існуючого репозиторію
Repository existingRepo = new FileRepositoryBuilder()
.setGitDir(new File("my_repo/.git"))
.build();
----

The builder has a fluent API for providing all the things it needs to find a Git repository, whether or not your program knows exactly where it's located.
It can use environment variables (`.readEnvironment()`), start from a place in the working directory and search (`.setWorkTree(…).findGitDir()`), or just open a known `.git` directory as above.
Будівник (builder) має легкий API для надання всіх даних, які йому потрібні для знайдення репозиторію -- знає ваша програма чи ні, де саме його розташовано.
Він може використовувати змінні середовища (`.readEnvironment()`), почати з поточної директорії та шукати (`.setWorkTree(…).findGitDir()`), чи просто відкрити відому директорію `.git`, як у прикладі вище.

Once you have a `Repository` instance, you can do all sorts of things with it.
Here's a quick sampling:
Щойно ви отримали примірник `Repository`, ви можете з ним робити будь-що.
Ось швидкі приклади:

[source,java]
----
// Get a reference
// Отримати посилання
Ref master = repo.getRef("master");

// Get the object the reference points to
// Отримати обʼєкт, на яке воно вказує
ObjectId masterTip = master.getObjectId();

// Rev-parse
ObjectId obj = repo.resolve("HEAD^{tree}");

// Load raw object contents
// Зчитати сирий вміст обʼєкту
ObjectLoader loader = repo.open(masterTip);
loader.copyTo(System.out);

// Create a branch
// Створити гілку
RefUpdate createBranch1 = repo.updateRef("refs/heads/branch1");
createBranch1.setNewObjectId(masterTip);
createBranch1.update();

// Delete a branch
// Вилучити гілку
RefUpdate deleteBranch1 = repo.updateRef("refs/heads/branch1");
deleteBranch1.setForceUpdate(true);
deleteBranch1.delete();

// Config
// Конфігурація
Config cfg = repo.getConfig();
String name = cfg.getString("user", null, "name");
----

There's quite a bit going on here, so let's go through it one section at a time.
Тут сталося чимало, отже розгляньмо кожну секцію окремо.

The first line gets a pointer to the `master` reference.
JGit automatically grabs the _actual_ master ref, which lives at `refs/heads/master`, and returns an object that lets you fetch information about the reference.
You can get the name (`.getName()`), and either the target object of a direct reference (`.getObjectId()`) or the reference pointed to by a symbolic ref (`.getTarget()`).
Ref objects are also used to represent tag refs and objects, so you can ask if the tag is ``peeled,'' meaning that it points to the final target of a (potentially long) string of tag objects.
Перший рядок отримує вказівник на посилання `master`.
JGit автоматично бере _справжнє_ посилання master, яке знаходиться в `refs/heads/master`, та повертає обʼєкт, який дозволяє вам отримувати інформацію про посилання.
Ви можете отримати назву (`.getName()`), та чи цільовий обʼєкт прямого посилання (`.getObjectId()`), чи посилання, на яке вказує символічне посилання (`.getTarget()`).
Обʼєкти посилань також використовуються для представлення посилань та обʼєктів теґів, отже ви можете спитати, чи ``очищено'' теґ, тобто чи вказує він на фінальну ціль (можливо довгого) рядку обʼєкту теґу.

The second line gets the target of the `master` reference, which is returned as an ObjectId instance.
ObjectId represents the SHA-1 hash of an object, which might or might not exist in Git's object database.
The third line is similar, but shows how JGit handles the rev-parse syntax (for more on this, see <<_branch_references>>); you can pass any object specifier that Git understands, and JGit will return either a valid ObjectId for that object, or `null`.

The next two lines show how to load the raw contents of an object.
In this example, we call `ObjectLoader.copyTo()` to stream the contents of the object directly to stdout, but ObjectLoader also has methods to read the type and size of an object, as well as return it as a byte array.
For large objects (where `.isLarge()` returns `true`), you can call `.openStream()` to get an InputStream-like object that can read the raw object data without pulling it all into memory at once.
Другий рядок отримує ціль посилання `master`, яке повернено як примірник ObjectId.
ObjectId репрезентує SHA-1 хеш обʼєкту, який може існувати чи не існувати в базі даних обʼєктів Git.
Третій рядок схожий, проте показує, як JGit працює з синтаксисом rev-parse (докладніше тут: <<_branch_references>>); ви можете передати будь-який специфікатор обʼєкту Git, який розуміє Git, та JGit поверне або чинний ObjectId цього обʼєкту, або `null`.

The next few lines show what it takes to create a new branch.
We create a RefUpdate instance, configure some parameters, and call `.update()` to trigger the change.
Directly following this is the code to delete that same branch.
Note that `.setForceUpdate(true)` is required for this to work; otherwise the `.delete()` call will return `REJECTED`, and nothing will happen.
Наступні два рядки показують, як зчитати сирий вміст обʼєкту.
У цьому прикладі, ми викликаємо `ObjectLoader.copyTo()`, щоб направити вміст обʼєкту напряму до stdout, проте ObjectLoader також має методи для зчитування типу та розміру обʼєкта, а також повернути його як масив байтів.
Для великих обʼєктів (для яких `.isLarge()` повертає `true`), ви можете викликати `.openStream()`, щоб отримати подібний до InputStream обʼєкт, який може читати дані сирого об'єкта без копіювання його в памʼять одразу.

The last example shows how to fetch the `user.name` value from the Git configuration files.
This Config instance uses the repository we opened earlier for local configuration, but will automatically detect the global and system configuration files and read values from them as well.
Наступні декілька рядків показують, що треба для створення нової гілки.
Ми створюємо примірник RefUpdate, налаштовуємо деякі параметри, та викликаємо `.update()`, щоб зробити зміни.
Безпосередньо далі наведено код для вилучення цієї ж гілки.
Зауважте, що `.setForceUpdate(true)` є необхідним щоб це спрацювало; інакше `.delete()` поверне `REJECTED`, і нічого не станеться.

This is only a small sampling of the full plumbing API; there are many more methods and classes available.
Also not shown here is the way JGit handles errors, which is through the use of exceptions.
JGit APIs sometimes throw standard Java exceptions (such as `IOException`), but there are a host of JGit-specific exception types that are provided as well (such as `NoRemoteRepositoryException`, `CorruptObjectException`, and `NoMergeBaseException`).
Останній приклад показує, як отримати значення `user.name` з конфігураційного файлу Git.
Примірник Config використовує сховище, яке ми відкрили раніше, для локальних налаштувань, проте автоматично знайде глобальні та системні конфігураційні файли, та також зчитає значення з них.

==== Porcelain
Це лише маленька вибірка повного кухонного API; у ньому доступно набагато більше методів та класів.
Також тут не показано, як JGit обробляє помилки, для чого використовуються винятки.
API JGit іноді кидає стандартні винятки Java (такі як `IOException`), проте також має дерево специфічних для JGit типів винятків, які надає бібліотека (такі як `NoRemoteRepositoryException`, `CorruptObjectException` та `NoMergeBaseException`).

The plumbing APIs are rather complete, but it can be cumbersome to string them together to achieve common goals, like adding a file to the index, or making a new commit.
JGit provides a higher-level set of APIs to help out with this, and the entry point to these APIs is the `Git` class:
==== Парадне

Кухонне API доволі повне, проте доволі громіздко складати виклики його функцій разом для вирішення поширених завдань, таких як додавання файлу до індексу, чи створення нового коміту.
JGit надає набір API вищого рівня щоб зарадити з цим, і вхідною точкою до цих API є клас `Git`:

[source,java]
----
Repository repo;
// construct repo...
// Створити репозиторій...
Git git = new Git(repo);
----

The Git class has a nice set of high-level _builder_-style methods that can be used to construct some pretty complex behavior.
Let's take a look at an example – doing something like `git ls-remote`:
Клас Git має гарний набір високорівневих методів _будівників_, які можна використати для створення доволі складної поведінки.
Подивімося на приклад, який робить щось на кшталт `git ls-remote`:

[source,java]
----
Expand All @@ -144,18 +145,18 @@ for (Ref ref : remoteRefs) {
}
----

This is a common pattern with the Git class; the methods return a command object that lets you chain method calls to set parameters, which are executed when you call `.call()`.
In this case, we're asking the `origin` remote for tags, but not heads.
Also notice the use of a `CredentialsProvider` object for authentication.
Це поширена практика з класом Git; методи повертають обʼєкти команди, що дозволяє вам створювати ланцюжок викликів для встановлення параметрів, які виконуються, коли ви викликаєте `.call()`.
У даному випадку, ми просимо віддалене сховище `origin` надати теґи, проте не звичайні посилання (heads).
Також зверніть увагу на використання обʼєкту `CredentialsProvider` для автентифікації.

Many other commands are available through the Git class, including but not limited to `add`, `blame`, `commit`, `clean`, `push`, `rebase`, `revert`, and `reset`.
Багато інших команд доступно в класі Git, включно з (проте не тільки) `add`, `blame`, `commit`, `clean`, `push`, `rebase`, `revert` та `reset`.

==== Further Reading
==== Додаткова література

This is only a small sampling of JGit's full capabilities.
If you're interested and want to learn more, here's where to look for information and inspiration:
Це лише маленька вибірка повних можливостей JGit.
Якщо ви зацікавлені та бажаєте дізнатись більше, ось де можна пошукати інформацію та натхнення:

* The official JGit API documentation is available online at http://download.eclipse.org/jgit/docs/latest/apidocs[].
These are standard Javadoc, so your favorite JVM IDE will be able to install them locally, as well.
* The JGit Cookbook at https://github.com/centic9/jgit-cookbook[] has many examples of how to do specific tasks with JGit.
* There are several good resources pointed out at http://stackoverflow.com/questions/6861881[].
* Офіційна документація JGit API доступна за адресою http://download.eclipse.org/jgit/docs/latest/apidocs[].
Це стандартний Javadoc, отже ваше улюблене JVM IDE буде в змозі також встановити цю документацію локально.
* JGit Cookbook (куховарська рецептів) за адресою https://github.com/centic9/jgit-cookbook[] містить багато прикладів виконання конкретних завдань за допомогою JGit.
* Є декілька добрих ресурсів, перелічених за адресою http://stackoverflow.com/questions/6861881[].
2 changes: 1 addition & 1 deletion status.json
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@
"B-embedding-git": {
"1-embedding-git.asc": 100,
"sections/command-line.asc": 100,
"sections/jgit.asc": 0,
"sections/jgit.asc": 100,
"sections/libgit2.asc": 100
},
"C-git-commands": {
Expand Down