Git
Since Camel 2.16
Both producer and consumer are supported
The Git component allows you to work with a generic Git repository.
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-git</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI Format
git://localRepositoryPath[?options]
URI Options
The producer allows doing operations on a specific repository. The consumer allows consuming commits, tags, and branches in a specific repository.
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Git component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
Used for enabling or disabling all consumer based health checks from this component. | true | boolean | |
Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true. | true | boolean |
Endpoint Options
The Git endpoint is configured using URI syntax:
git:localPath
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The name of the branch. The commit consumer receives the commits reachable from it, or the commits of all refs when it is not set or not found. For the producer it is the branch to create or delete, to check out (clone and checkout, which creates it when it does not exist) or to merge into targetBranchName (merge), and add, remove, commit, commitAll, status, log, push, pull, cherryPick and clean check out this existing branch first. | String | ||
If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | false | boolean | |
What the consumer receives: commit for each commit, tag for each tag, or branch for each local and remote-tracking branch. Required for the consumer. It receives all the existing items on its first poll and keeps the consumed ones in memory only, so after a restart it receives all of them again. Enum values:
| GitType | ||
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | PollingConsumerPollStrategy | ||
Whether commit and commitAll create a commit when there is nothing to commit. If false, they fail with the EmptyCommitException of JGit instead, as git commit does without --allow-empty. The CamelGitAllowEmpty header replaces this option. | true | boolean | |
The depth of a shallow clone in the clone operation, as the number of commits of history to fetch. For example, 1 fetches only the latest commit. The default 0 makes a full clone, and a negative value fails the clone. | int | ||
The operation that the producer performs. If not set, the producer takes it from the CamelGitOperation header. Enum values:
| String | ||
The name of the remote, such as origin, that pull, push and pushTag use and that remoteAdd adds. Required by these operations. | String | ||
The URL of the remote repository, such as https://github.com/apache/camel.git. The clone operation clones it, and remoteAdd adds it as the remote named remoteName. | String | ||
The name of the tag for createTag, which creates an annotated tag of HEAD, and for deleteTag and pushTag. For checkout, the tag that the new branchName branch starts from. | String | ||
The branch that the merge operation checks out and merges branchName into. If not set, merge uses init.defaultBranch of the user git config, or master when that is not set either. | master | String | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
The git config file to read in place of the user git config (/.gitconfig), as a URI with the classpath:, file:, http: or https: scheme. When it is set, the system git config is not read. | String | ||
The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | int | ||
The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | int | ||
To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | int | ||
Milliseconds before the next poll. | 500 | long | |
If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean | |
How long a poll may run before the health check of the consumer reports DOWN. The health check is otherwise based on the polls that are done, so it stays UP while a poll hangs, for example on a read without timeout from a connection that went silent. A poll includes routing the messages it polled, so set this above the longest poll you expect. The poll is not interrupted. The value is in millis (not affected by timeUnit). The default 0 turns this off. | 0 | long | |
Milliseconds before the first poll starts. | 1000 | long | |
Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. | 0 | long | |
The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. Enum values:
| TRACE | LoggingLevel | |
Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | ScheduledExecutorService | ||
To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler. | none | Object | |
To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. This is a multi-value option with prefix: scheduler. | Map | ||
Whether the scheduler should be auto started. | true | boolean | |
Time unit for initialDelay and delay options. Enum values:
| MILLISECONDS | TimeUnit | |
Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean | |
The password, or an access token, to authenticate with the remote repository in clone, pull, push and pushTag. Used only when username is set too. | String | ||
The user name to authenticate with the remote repository in clone, pull, push and pushTag. Used only when password is set too. | String |
Message Headers
The Git component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The operation that the producer performs, used only when the operation option is not set. | String | |
| Constant: | The path of the file to stage (add) or to remove from the index and the working tree (remove), relative to the root of the working tree with / as separator. A directory stands for all the files below it, and file globs are not supported. Required by add and remove. | String | |
CamelGitCommitMessage (producer) Constant: | The message of the new commit in commit and commitAll. Required by both. | String | |
CamelGitCommitUsername (producer) Constant: | The name of the author and committer of the new commit in commit and commitAll. Used only together with CamelGitCommitEmail. Without both, JGit takes them from user.name and user.email of the git config. | String | |
CamelGitCommitEmail (producer) Constant: | The email of the author and committer of the new commit in commit and commitAll. Used only together with CamelGitCommitUsername. | String | |
| Constant: | The commit id (the sha): of the commit consumed by the commit consumer, of the commit to cherry pick in a cherryPick operation, and of the new commit after a commit or commitAll operation. | String | |
| Constant: | Whether commit and commitAll create a commit when there is nothing to commit. Replaces the allowEmpty option. | Boolean | |
| Constant: | The name of the author of the consumed commit. | String | |
CamelGitCommiterName (consumer) Constant: | The name of the committer of the consumed commit. | String | |
| Constant: | The commit time of the consumed commit, in seconds since 1970-01-01T00:00:00Z. | int | |
| Constant: | The full name of the consumed ref, such as refs/heads/main, refs/remotes/origin/main or refs/tags/v1. The branch and tag consumers set it and also put it in the body. | String | |
| Constant: | The full name of the ref that the consumed ref points to in the end, when it is a symbolic ref such as refs/remotes/origin/HEAD. For any other ref it is the same as CamelGitBranchName. | String | |
CamelGitBranchObjectId (consumer) Constant: | The id of the object that the consumed ref points to: a commit for a branch or a lightweight tag, a tag object for an annotated tag. | String |
Message Body
The message body at each side of the Git component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| The full message of the commit with type=commit, the name of the ref, such as refs/heads/main or refs/tags/v1, with type=branch and tag. The commit id, author, committer and time, or the object id of the ref, are in headers. |
Producer input |
| Not used: the operations take their input from the options and headers, such as the file in CamelGitFilename and the message in CamelGitCommitMessage. |
Producer output |
| The result of JGit for the operation: the Status of status, the commits of log as a RevWalk read once, a List of Refs for showBranches and showTags, the PushResults of push, the Properties of the statistics of gc. The operations that change the repository, such as add and commit, keep the body. Without the operation option the operation is taken from the CamelGitOperation header.
|
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Examples
Producer Example
Below is an example route of a producer that adds a file test.java to a local repository, commits it with a specific message on the main branch and then pushes it to remote repository.
from("direct:start")
.setHeader("CamelGitFilename", constant("test.java"))
.to("git:///tmp/testRepo?operation=add")
.setHeader("CamelGitCommitMessage", constant("first commit"))
.to("git:///tmp/testRepo?operation=commit")
.to("git:///tmp/testRepo?operation=push&remotePath=https://foo.com/test/test.git&username=xxx&password=xxx")
.to("git:///tmp/testRepo?operation=createTag&tagName=myTag")
.to("git:///tmp/testRepo?operation=pushTag&tagName=myTag&remoteName=origin"); Consumer Example
Below is an example route of a consumer that consumes commit:
-
Java
-
XML
-
YAML
from("git:///tmp/testRepo?type=commit")
.to("mock:result"); <route>
<from uri="git:///tmp/testRepo?type=commit"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: git:///tmp/testRepo
parameters:
type: commit
steps:
- to:
uri: mock:result The consumer polls the repository with the scheduler options of the endpoint, such as delay (500 milliseconds by default) and initialDelay. Each poll walks the history of the branch, or lists the tags or the branches, to find the items that it has not delivered yet, so raise delay for a large repository that changes seldom.
A commit, tag or branch is marked consumed only when the route processed it without a failure. When the exchange fails, the failure is reported to the exception handler of the consumer, and the item is delivered again on the next poll. It then comes after the items that followed it in the same poll, which were already delivered: the commits come from the newest to the oldest, and the tags and the branches in the order of their names.
A poll counts only the items that it marked consumed. After a poll whose items all failed, a greedy consumer does not poll again at once and sendEmptyMessageWhenIdle sends no empty message, while backoffIdleThreshold and backoffMultiplier count it as an idle poll, so they can slow down the retries of an item that keeps failing. When an item keeps failing, handle the failure in the route, for example with a dead letter channel or a handled onException, so that the item is marked consumed.
Shallow Clone
Use the depth option to perform a shallow clone, fetching only a limited number of commits. This reduces clone time and disk usage for large repositories when full history is not needed.
-
Java
-
XML
-
YAML
from("direct:clone")
.to("git:///tmp/myRepo?operation=clone&remotePath=https://github.com/example/repo.git&depth=1"); <route>
<from uri="direct:clone"/>
<to uri="git:///tmp/myRepo?operation=clone&remotePath=https://github.com/example/repo.git&depth=1"/>
</route> - route:
from:
uri: direct:clone
steps:
- to:
uri: git:///tmp/myRepo
parameters:
operation: clone
remotePath: "https://github.com/example/repo.git"
depth: 1 A depth of 1 fetches only the latest commit. The value must be a positive integer. When set to 0 or omitted, a full clone is performed.
Custom config file
By default, camel-git will load .gitconfig file from user home folder. You can override this by providing your own .gitconfig file.
from("git:///tmp/testRepo?type=commit&gitConfigFile=file:/tmp/configfile")
.to(....); // will load from os dirs
from("git:///tmp/testRepo?type=commit&gitConfigFile=classpath:configfile")
.to(....); // will load from resources dir
from("git:///tmp/testRepo?type=commit&gitConfigFile=http://somedomain.xyz/gitconfigfile")
.to(....); // will load from http. You could also use https