GitHub API в Java
Я знаю, что GitHub используется для отслеживания версий проекта. Как им пользоваться? И можно ли сделать так чтобы, к примеру, я написал код на java, загрузил его в свой репозиторий, и у клиента выполняется этот код выполняется? Если можно, то как?
Отслеживать
user236980
задан 13 сен 2013 в 23:19
delphikettle delphikettle
1,330 4 4 золотых знака 24 24 серебряных знака 48 48 бронзовых знаков
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
GitHub — это хостинг Git — это система управления версиями Jenkins — это инструмент, для непрерывной интеграции
- установить git и приблизительно научится им пользоваться
- выбрать сервер для хранения кода, это может быть github, но он платный для приватных проектов (есть много хороших бесплатных аналогов)
- попробовать разобраться с jenkins — с его помощью можно «выполнять код у клиента», делать билды по разписанию, гонять тесты
Отслеживать
user181100
ответ дан 14 сен 2013 в 7:05
12.4k 1 1 золотой знак 20 20 серебряных знаков 43 43 бронзовых знака
Можно поподробнее о бесплатных аналогах?
14 сен 2013 в 9:42
xp-dev.com, assembla.com, bitbucket.org
14 сен 2013 в 9:57
- github
- java
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.10.27.43697
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
A2.3 Приложение B: Встраивание Git в ваши приложения — JGit
Если вы хотите использовать Git из Java-программ, существует библиотека для работы с Git, называемая JGit. Она достаточно полно реализует функциональность Git, написана на чистом Java и широко используется Java сообществом. Проект JGit находится под опекой Eclipse и расположен по адресу https://www.eclipse.org/jgit.
Приступая к работе
Существует несколько способов добавить JGit в проект и начать писать код с использованием предоставляемого API. Возможно, самый простой путь — использование Maven: подключение библиотеки происходит путём добавления следующих строк в секцию в вашем pom.xml:
org.eclipse.jgit org.eclipse.jgit 3.5.0.201409260305-r
С момента выхода книги скорее всего появились новые версии JGit, проверьте обновления на https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit. После обновления конфигурации Maven автоматически скачает JGit нужной версии и добавит её к проекту.
Если вы управляете зависимостями вручную, собранные бинарные пакеты JGit доступны на https://www.eclipse.org/jgit/download. Использовать их в своём проекте можно следующим способом:
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
Служебный API
У JGit есть два уровня API: служебный («plumbing» API, «трубопровод») и пользовательский («porcelain» API, «фарфор»). Эта терминология заимствована из самого Git и JGit разделён на две части: «фарфоровый» API предоставляет удобные методы для распространённых задач прикладного уровня (тех, для решения которых вы бы использовали обычные Git-команды) и «сантехнический» API для прямого взаимодействия с низкоуровневыми объектами репозитория.
Начальная точка большинства сценариев использования JGit — класс Repository и первое, что необходимо сделать — это создать объект данного класса. Для репозиториев основанных на файловой системе (да, JGit позволяет использовать другие модели хранения) эта задача решается с помощью класса FileRepositoryBuilder :
// Создание нового репозитория; каталог должен существовать Repository newlyCreatedRepo = FileRepositoryBuilder.create( new File("/tmp/new_repo/.git")); newlyCreatedRepo.create(); // Открыть существующий репозиторий Repository existingRepo = new FileRepositoryBuilder() .setGitDir(new File("my_repo/.git")) .build();
Вызовы методов билдера можно объединять в цепочку чтобы указать всю информацию для поиска репозитория независимо от того, знает ли ваша программа его точное месторасположение или нет. Можно читать системные переменные ( .readEnvironment() ), начать поиск с произвольного места в рабочем каталоге ( .setWorkTree(…).findGitDir() ), или просто открыть каталог .git по указанному пути.
После создания объекта типа Repository , вам будет доступен широкий набор операций над ним. Краткий пример:
// Получение ссылки Ref master = repo.getRef("master"); // Получение объекта, на который она указывает ObjectId masterTip = master.getObjectId(); // Использование синтаксиса rev-parse ObjectId obj = repo.resolve("HEAD^"); // Получение «сырых» данных ObjectLoader loader = repo.open(masterTip); loader.copyTo(System.out); // Создание ветки RefUpdate createBranch1 = repo.updateRef("refs/heads/branch1"); createBranch1.setNewObjectId(masterTip); createBranch1.update(); // Удаление ветки RefUpdate deleteBranch1 = repo.updateRef("refs/heads/branch1"); deleteBranch1.setForceUpdate(true); deleteBranch1.delete(); // Работа с конфигурацией Config cfg = repo.getConfig(); String name = cfg.getString("user", null, "name");
Тут происходит много интересного, давайте разберёмся по порядку.
Первая строка получает указатель на ссылку master . JGit автоматически получает актуальную информацию о master , хранимую по пути refs/heads/master , и возвращает объект, предоставляющий доступ к информации о ссылке. Вы можете получить имя ( .getName() ), а также целевой объект прямой ссылки ( .getObjectId() ) или ссылку, на которую указывает другая символьная ссылка ( .getTarget() ). Объекты типа Ref также служат для представления ссылок на теги и самих тегов; вы можете узнать, является ли тег «конечным» («peeled»), т. е. ссылается ли он на целевой объект потенциально длинной цепи тегов.
Вторая строка получает объект на который указывает ссылка master в виде ObjectId. ObjectId представляют SHA-1-хеш объекта, который, возможно, сохранён внутри базы данных объектов Git. Следующая строка похожа на предыдущую, но используется синтаксис rev-parse (см. детали в разделе Ссылки на ветки главы 7); вы можете использовать любой, подходящий формат и JGit вернёт либо валидный ObjectId для указанного объекта, либо null .
Следующие две строки показывают, как можно получить содержимое объекта. В этом примере мы используем ObjectLoader.copyTo() чтобы передать содержимое файла прямиком в stdout, но у ObjectLoader есть методы для чтения типа и размера объекта, а также для считывания объекта в виде массива байтов. Для больших объектов (у которых .isLarge() возвращает true ) можно использовать метод .openStream() для открытия потока последовательного чтения объекта без полной загрузки в память.
Следующие строки показывают, как создать новую ветку. Мы создаём объект типа RefUpdate, устанавливаем некоторые параметры и вызываем метод .update() чтобы инициировать изменение. После этого мы удаляем эту же ветку. Обратите внимание на необходимость вызова .setForceUpdate(true) для корректной работы; иначе вызов .delete() вернёт REJECTED и ничего не произойдёт.
Последний кусок кода показывает как получить параметр user.name из файлов конфигурации Git. Созданный объект Config будет использовать открытый ранее репозиторий для чтения локальной конфигурации, также он автоматически находит файлы глобальной и системной конфигурации и использует их для чтения значений.
Это лишь малая часть служебного API JGit; в вашем распоряжении окажется гораздо больше классов и методов. Мы не показали как JGit обрабатывает ошибки. JGit использует механизм исключений Java; иногда он бросает стандартные исключения (типа IOException ), иногда — специфичные для JGit (например NoRemoteRepositoryException , CorruptObjectException и NoMergeBaseException ).
Пользовательский API
Служебные API достаточно всеобъемлющи, но сложны в использовании для простых задач вроде добавления файла в индекс или создания нового коммита. У JGit есть API более высокого уровня, входная точка в который — это класс Git :
Repository repo; // создание репозитория. Git git = new Git(repo);
В классе Git можно найти отличный набор высокоуровневых «текучих» методов (builder-style / fluent interface). Давайте взглянем на пример — результат выполнения этого кода напоминает git ls-remote :
CredentialsProvider cp = new UsernamePasswordCredentialsProvider("username", "p4ssw0rd"); Collection remoteRefs = git.lsRemote() .setCredentialsProvider(cp) .setRemote("origin") .setTags(true) .setHeads(false) .call(); for (Ref ref : remoteRefs) < System.out.println(ref.getName() + " ->" + ref.getObjectId().name()); >
Тут показан частый случай использования класса Git: методы возвращают тот же объект, на котором вызваны, что позволяет чередовать их друг за другом, устанавливая параметры, а выполнение происходит при вызове .call() . В этом примере мы запрашиваем с удалённого репозитория origin список тегов, исключая ветки. Обратите внимание на использование класса CredentialsProvider для аутентификации.
Множество команд доступно в классе Git, включая такие как add , blame , commit , clean , push , rebase , revert , reset и другие.
Дополнительные материалы
Это лишь небольшой пример всех возможностей JGit. Если вы заинтересованы в более детальной работе с JGit, вот список источников информации для старта:
- Официальная документация по JGit API доступна в Интернете на https://www.eclipse.org/jgit/documentation. Это обыкновенный Javadoc, так что ваша любимая IDE может скачать её и использовать оффлайн.
- «Поваренная книга» JGit, расположенная по адресу https://github.com/centic9/jgit-cookbook, включает в себя много готовых рецептов использования JGit для решения тех или иных задач.
How to Improve Your Java Workflow with GitHub API
By now, you have probably heard about the GitHub API. Or you know what GitHub is and you know what an API is. Or you just Googled it, that’s okay too.
From automating GitHub processes to just being a command line fanatic, the GitHub API can be used in many different ways. By taking a brief look at the documentation, you can see the GitHub API can do just about everything and more.
Stay tuned to find out many cool features you probably didn’t know the GitHub API has and make your automation process a walk in the park.
Read to the end for a quick and easy tutorial!
The Convenience of GitHub API
As many enterprises use GitHub in their everyday work, it may not come as a surprise to learn the base URL can be different from those which are public repositories.
The most difficult part in the entire process is actually this — find out what the base URL of your enterprise is. Seems easy, right? The base URL of your enterprise can look something like https://.githubname.com/api/v3 .
The v3 in this case stands for version 3, the current version of the GitHub API,while the public GitHub base URL is https://api.github.com .
Once you have found the base URL, keep it somewhere safe — perhaps the part of your brain where it will never be forgotten, you’ll most likely need to create a Personal Access Token (PAT). This can be done by following the official GitHub docs tutorial. If you already have a token, you can just use that one.
You’ll need this token for any kind of request that requires authorization, especially if you want to do more complex tasks than just calling a few GET requests against a public GitHub repository. For these requests, you’ll need to add a Header to the request as such:
"Authorization": "Bearer []"
Now you’re ready to dive into the fun world of making requests.
SHA-1 values
To make everything easier to find and understand, commits in git have their own Secure Hash Algorithm 1 (SHA-1) value. Other objects in GitHub have sha tokens that point back to the commit, so we can identify the objects using these values.
The easiest way to obtain an SHA-1 value for an object is to store the response when creating said object.
The other way is to fish out the value through a GET request against the object. This way is slightly more difficult, as you would need to know specific information such as an exact pull request number, commit number, or branch name.
Creating and deleting references
Any self-respecting software engineer will tell you to never simply push your code to the master branch. Instead you need to manually create a new branch every time run the code you’d like to automate. That seems quite upsetting.
Just as you’re wondering if there’s even hope to ever sit back and sip your coffee while your code just does its thing, the GitHub API comes to the rescue.
You can create branches with one request:
POST /repos/:owner/:repo/git/refs
That has required 2 body parameters:
- ref (string) — the name of the branch you’d like to create (i.e refs/heads/[your_branch_name])
- sha (string) — sha token value of the branch you’d like to create a branch on
After hitting send, your new branch will appear like clockwork.
Getting tired of your new snazzy branch? Has it served its purpose? Perhaps you named it incorrectly? Fear not, you can also delete the reference without leaving a trace through the GitHub API. All you’ll need is the name of the branch you just created.
DELETE /repos/:owner/:repo/git/refs/:ref
Poof, gone. Nobody will ever need to know.
Creating and updating content
Say you’re using a dependency in a project and you always want to have the latest version on hand. Why waste your valuable time on doing things manually, when you can just click one button and have a computer update the dependencies for you? I mean, that’s where we’re headed with automation, right?
Yet again, the GitHub API can create or update content with a simple request.
PUT /repos/:owner/:repo/contents/:path
The request will create a commit. This time, you’ll have 2 required body parameters (3 if you’re looking to update an existing file):
- message (string) — the commit message
- content (string) — the content of the entire file in Base64 encoding. You can use the built-in Java Base64 functionality.
- sha (string) — the blob SHA of the file being replaced (necessary only if updating a file)
There are a few optional parameters, but if you feel like using your flashy new branch, you can add an extra parameter:
- branch (string) — the name of your branch
A commit will have been created and your file successfully created/updated. You can thank the GitHub API later.
Manage pull requests (PRs)
As you may have guessed by now, the GitHub API can handle PRs without you having to leave the comfort of your command line or your favourite IDE.
The GitHub API can open PRs, merge them, add reviews to them and so on, but out of the many capabilities, a favorite task has to be- checking their statuses.
Depending on where you work, the PRs may have several checks that have to pass before they can be merged to the master branch. Imagine having a process automated, but not being able to merge your branch, because it’s just not ready yet.
Our superhero of the day can and will assist you. You can use this request to check the status of your PR.
GET /repos/:owner/:repo/commits/:ref/status
In this case, the ref would be the SHA of one of the commits in your PR.
The status of a PR can either be pending, success or failure. Adding a simple while loop and checking in every now and then will allow your code to keep running after a small wait for your PR to be in the success status.
Let’s Get Started
After all of that reading, it’s time for you to warm up your fingers with a quick exercise. We’ll create a Java project that calls the GitHub API to create a branch, create a file, create a pull request, merge the pull request and delete the branch.
Setup
If at any point you are having any trouble, you can refer to the working code on my personal GitHub.
In this example, I will be creating my project as a Maven project, so I could use third party libraries without having to find them, download them and add them to my classpath.
Using JetBrains IntelliJ, select New Project.
From the dropdown menu on the left, select Maven.

Choose your cloned repository and name the project as you wish. For the purpose of this article, I’m naming the project as “github-api-test”, as seen in the screenshot below:

Your project structure should look like this. You can take a look at the pom.xml file and get acquainted. Also set the maven compiler version here as we will be using Java 11 features:
11 11

Start by creating a new Java class like so:

Before diving into everything, we can make our lives easier by preparing 4 different requests: GET, PUT, POST and DELETE — these requests will return us the response body. To get a better understanding of this, you can check out 5 ways to make HTTP requests in Java. We will be reusing these methods to avoid writing duplicate code. To keep things simple and maintainable, we’ll have a few constants — the base URL of your GitHub and your PAT. We will also be adding an object mapper, more about this in Three ways to use Jackson for JSON in Java. Add these to the very beginning of your class.
private static final String authorization = "Bearer "; private static final String baseUrl = "https://api.github.com/repos//"; private static final ObjectMapper objectMapper = new ObjectMapper();
private String get(String path) throws IOException, InterruptedException
As you can see from the example, we’ll first be preparing a new HTTP request using the Java 11 HttpClient. For this, we’re using a builder, in which you can create a URI, add headers and parameters. Finally, we will be creating a new HTTP client for each request and sending it. For this request, we’ll only have 1 parameter, which is the path after the base URL.
private String delete(String path) throws IOException, InterruptedException
Similarly to the GET request, we only have 1 parameter — the path.
private String post(String path, String body) throws IOException, InterruptedException
In the POST request, we’ll have an extra parameter — the body we would like to send with the request.
private String put(String path, String body) throws IOException, InterruptedException
This one is similar to the POST request, having 2 parameters.
In order to use the dependencies I have used in this project, open the pom.xml file and add the following right before the tag:
com.fasterxml.jackson.core jackson-databind 2.11.2
This is a JSON library, which we can use for parsing JSON (all HTTP responses are in JSON form, so anything you would like to read out, you need to parse.
After adding these to the pom.xml file, you should see a small m symbol and a refresh button in the right corner — you should click that. It will look like this:

Two small steps before diving in, you’ll want to create a resource file (you can chose the content and filetype you desire):

Now we’ll add an extra method for reading the contents of this file to a string.
private String getResourceFile(String filename) throws IOException
If this method seems confusing at the moment, don’t worry about it. The tutorial isn’t about this complicated step and everything else will be easier to understand. The main point — it takes in the resource file, reads the content and returns a String of the content.
Make Requests with GitHub API
It’s finally time to start making those requests! Let’s start off by finding out what the SHA value of our master branch is.
private String getMasterBranchSHA() throws IOException, InterruptedException < var body = this.get("/git/refs/heads"); var sha = objectMapper.readTree(body) .get(0) .get("object") .get("sha") .asText(); return sha; >
Here we will be using our own GET method we created earlier by using the path /git/refs/heads . GitHub API responses vary from JSON objects to JSON arrays, it’s kind of a trial and error in the beginning. In this case, we have received a JSON array and will be parsing it accordingly. Lastly, we will return the SHA value as a String.
Next, let’s create that snazzy new branch I know you’ve been dreaming about for a while now.
private String createBranch(String sha) throws IOException, InterruptedException < var createBranchMap = Map.of( "ref", "refs/heads/new-branch", "sha", sha); var requestBody = objectMapper.writeValueAsString(createBranchMap); return this.post("/git/refs", requestBody); >
In the beginning we will be creating a Map and adding the values we would like to add to the request body — in this case they are ref (the name of the new branch, i.e refs/heads/) and sha , which is the same SHA value we just found with the getMasterBranchSHA method.
After that’s written, we can create the file we wish to upload.
private String createFile() throws IOException, InterruptedException < var fileToAdd = getResourceFile("new_file.txt"); var encodedContent = java.util.Base64.getEncoder().encodeToString(fileToAdd.getBytes()); var createMap = Map.of( "message", "New file added", "content", encodedContent, "branch", "new-branch"); var requestBody = objectMapper.writeValueAsString(createMap); return this.put("/contents/new_file.txt", requestBody); >
Here we will be using the method we created earlier — getResourceFile . We will be encoding the String contents of the file through Base64. After that, we create the request body, where message will be the commit message, content will be the encoded file content and branch will be our new branch name. We use the PUT request we created earlier and send the request.
Now we can create a pull request.
private String createPullRequest() throws IOException, InterruptedException < var createPullRequestMap = Map.of( "title", "test-pull-request", "head", "new-branch", "base", "master"); var requestBody = objectMapper.writeValueAsString(createPullRequestMap); return this.post("/pulls", requestBody); >
As per prior methods, here we will create the request body, where title will be the PR title, the head will be the branch we would like to make a PR from and the base will be the branch we would like to merge into.
When the pull request is ready, we can merge the branch.
private String getPullNumber(String pullRequestResponse) throws JsonProcessingException < return objectMapper.readTree(pullRequestResponse) .get("number") .asText(); >private String mergePullRequest(String pullNumber) throws IOException, InterruptedException < var mergeMap = Map.of( "commit_message", "Merging pull request"); var requestBody = objectMapper.writeValueAsString(mergeMap); var url = String.format("/pulls/%s/merge", pullNumber); return this.put(url, requestBody); >
To merge the PR, we will need the PR number, which we can get by parsing the JSON response of the PR creation response. To merge the branch, we will create a request body, where commit_message will be details about the merge.
After our branch has served its purpose, we can just go ahead and get rid of it.
private String deleteBranch() throws IOException, InterruptedException < return this.delete("/git/refs/heads/new-branch"); >
This one is pretty straightforward — all we do is send a DELETE request with the branch name.
Now that we have all the necessary pieces of the puzzle, we can put it together so it could run with just one push of a button.
private void executeExample() throws IOException, InterruptedException
Now we can create the main method and reap the rewards of our hard work. Add this straight under the constants and straight above all the other methods.
public static void main(String[] args) throws IOException, InterruptedException
After you compile and run the code, you can head to your GitHub repo and look at the commit history. It should look like this:

As you can see, the file we wanted to add has been added and the branch deleted.

What else can I do?
The GitHub API is capable of so much more than we did today. If you’re interested in what else you can accomplish using this undemanding tool, go ahead and read the GitHub API documentation.
Overall, I feel it’s needless to say the GitHub API deserves a cape and a cool superhero pose.
Emily Joy Krohn is an intern on Twilio’s messaging team. She is in her third year of software engineering at the Tallinn University of Technology. You can take a look at her LinkedIn profile to get to know her better. You can also send an email with any questions or comments you’d like to share to emilyjkrohn@gmail.com.
Rate this post
- Diane Phan
- Matthew Gilliard
Not ready yet? Talk to an expert.
- About
- Legal
- Copyright © 2023 Twilio Inc.
- All Rights Reserved.
- Protected by reCAPTCHA – Privacy – Terms
RestAPI + Java+spring. Часть 2 — создаем проект, добавляем его на github.
Статья о том, как создать репозиторий на github и как добавить в этот репозиторий новый проект.
В предыдущей статье мы рассмотрели общую концепцию нашего проекта, определили примерно, какое flow проекта, какие есть объекты, какую базу данных мы будем использовать.
Теперь пришло время начинать писать проект.
Создаем репозиторий на github
Для того, что бы добавить проект в репозиторий github, необходимо сначала создать этот репозиторий.
- переходим в свой профиль на github. Находим кнопку NEW и нажимаем на нее.
- попадаем на страницу создания репозитория. Заполняем поля.
наш репозиторий будет называться item
- заполняем поля
- нажимаем кнопку “create repository”.
Все! Репозиторий создан, в нем на данный момент есть Readme файл — это файл, в котором обычно пишут описание проекта и всю необходимую для его запуска информацию, и gitignore файл. В этом файле хранится список тех файлов, которые мы не хотим “заливать” на git.
Клонирование репозитория на локальный компьютер
После того, как мы создали репозиторий, нужно “склонировать” его на свой компьютер.
- на github нажимаем кнопку “Code” и копируем ссылку, которую увидим там.
- переходим в Terminal на компьютере. Переходим в нужную нам директорию (у меня это Desktop)
- клонируем репозиторий. Для того, что бы склонировать, нужно ввести команду git clone и вставить ссылку, которую мы скопировали на гите.
После того, как мы увидим слово “done” мы можем перейти в директорию, куда мы копировали проект и увидеть, что была создана папка с проектом, в которую был добавлен код. Пока в этой папке всего один файл, но это уже проект. Его можно открыть в среде разработки (я использую Intellij)
Добавляем Maven
Второй шаг, который необходимо сделать до того, как начнем писать логику приложения — сделать из нашего “файлика” спринг проект и добавить зависимости.
Для этого переходим на сайт https://start.spring.io/ и заполняем там необходимые поля
например — вот так. Если мы забыли добавить какую то зависимость — мы всегда можем это сделать по мере необходимости. Пока мы добавили:
- Ломбок — помогает уменьшить количество кода
- базу данных
- валидаор
- актуатор — поможет проверять состояние приложения. Например — всегда можно проверить запущено оно или “лежит” по какой либо причине. Это полезно если ваше приложение где то в “облаке”
Теперь, когда все данные добавлены — можно генерировать проект и скачивать его. Нажимаем кнопку
Ждем пока проект сгенерируется и скачается. После окончания скачивания делаем следующие действия —
- открываем проект в среде разработки
- распаковываем архив items и видим там файл pom.xml
- копируем pom.xml в корневую директорию проекта
Если сейчас запустить инсталяцию мавен — то мы увидим проблему —
все логично. Дело в том, что Spring требует определенную структуру для своих проектов. А именно — необходим main class которого у нас пока нет. Создаем его.
можно создать структуру “руками”, а можно просто скопировать папку src из items ( архива, полученного с сайта start.spring.io)
в любом случае у нас должна получится вот такая структура
теперь в папке java добавляем структуру именно нашего проекта. Если мы откроем pom.xml мы увидим в нем
groupId тут — это путь к нашим классам. Создаем его физически, и сразу де создаем main класс.
Осталось сделать из этого класса main class. Для этого, нам необходим метод main и аннотация, которая скажет спрингу, что это и есть главный класс.
@SpringBootApplication - говорит о том, что это именно приложение построенное с помощью Spring.
пробуем запустить maven — переходим в терминал, в папку приложения
и вводим команду
Видим что все ОК. Пробуем запустить приложение —
все в порядке. Приложение стартануло. Теперь пора добавить все изменения на gitHub
Добавляем изменения на GitHub
smilyk@MBP-Smilyk items % git add . — этп команда добавляет все файлы в localgit
Нам не нужны все файлы в репозитории. Нам нужны там только те файлы, которые отвечают за логику, а все дополнительные (типа файлов мавен) там не нужны. Поэтому добавляем файлы по одному.
smilyk@MBP-Smilyk items % git add src
видим, что для комита добавлена директория src. Так же добавляем pom.xml.
Больше пока нам ничего добавлять не нужно.
Следующий шаг — коммитим эти изменения, добавив комментарий “init project”
smilyk@MBP-Smilyk items % git commit -m “init project”
и, наконец, пушим все наши коммиты на git
Переходим на github
И видим — все наши изменения сохранены в удаленный репозиторий!
Задача этой статьи выполнена. У нас есть Spring Boot проект, который хранится в удаленном репозитории на github.
В следующей статье мы можем начать подключать базу данных и писать логику.