java-cmd's People
Forkers
mourav2222java-cmd's Issues
Пишем клиент для GitHub Issue
Подключаем зависимости:
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-jackson:2.9.0")
Создаем класс Issue
@JsonIgnoreProperties(ignoreUnknown = true)
public class Issue {
private int id;
private Integer number;
private String title;
private String state;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
Создаем класс GitHubService
public interface GitHubService {
@GET("repos/{owner}/{repo}/issues")
Call<List<Issue>> getIssues(@Path("owner") String user,
@Path("repo") String repo);
@GET("repos/{owner}/{repo}/issues/{number}")
Call<Issue> getIssue(@Path("owner") String user,
@Path("repo") String repo,
@Path("number") int number);
@PATCH("repos/{owner}/{repo}/issues/{number}")
Call<Issue> updateIssue(@Path("owner") String user,
@Path("repo") String repo,
@Path("number") Integer number,
@Body Issue issue);
}
Создаем класс AuthInterceptor
public class AuthInterceptor implements Interceptor {
private final String token;
public AuthInterceptor(final String token) {
this.token = token;
}
@Override
public Response intercept(Chain chain) throws IOException {
final Request request = chain.request().newBuilder()
.addHeader("Authorization", String.format("token %s", token)).build();
return chain.proceed(request);
}
}
Создаем класс RetrofitUtil
public class RetrofitUtil {
public static Retrofit createRetrofit() throws IOException {
final Path tokenFile = Paths.get(System.getProperty("user.home")).resolve("token");
final String token = Files.readAllLines(tokenFile).get(0).trim();
return createRetrofit("https://api.github.com/", token);
}
public static Retrofit createRetrofit(final String endpoint, final String token) {
final OkHttpClient.Builder builder = new OkHttpClient.Builder();
Optional.ofNullable(token)
.map(AuthInterceptor::new)
.ifPresent(builder::addInterceptor);
return new Retrofit.Builder()
.addConverterFactory(JacksonConverterFactory.create())
.client(builder.build())
.baseUrl(endpoint)
.build();
}
}
Создаем класс Tester
public class Tester {
public static void main(String[] args) {
final GitHubService github = createRetrofit().create(GitHubService.class);
final Response<Issue> response = github.getIssue("eroshenkoam", "allure-example", 1).execute();
if (response.isSuccessful()) {
final Issue issue = response.body();
System.out.println(String.format("#%d [%s] %s", issue.getNumber(), issue.getState(), issue.getTitle()));
} else {
System.out.println(response.errorBody().string());
}
}
}
Добавляем сборку через GraalVM
Добавляем зависимости:
plugins {
java
id("com.palantir.graal") version("0.6.0")
}
Добавляем конфигурацию:
graal {
mainClass("io.github.eroshenkoam.cmd.Tester")
outputName("tester")
}
Делаем сборку:
./gradlew clean nativeImage
Выполняем запрос:
./build/graal/tester issue-get --owner eroshenkoam --repo allure-example --number 10
Добавляем скрипты для GH Actions
Скрипт для сборки в файле .github/workflows/build.yml
:
name: Build
on:
pull_request:
branches:
- '*'
push:
branches:
- 'master'
jobs:
build:
runs-on: ${{ matrix.os }}-latest
strategy:
matrix:
os: [ubuntu, macos]
steps:
- uses: actions/checkout@v1
- name: Set up JDK
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: "Build"
run: ./gradlew nativeImage
Скрипт для релиза в файле .github/workflows/release.yml
:
name: Release
on:
release:
types: [published]
jobs:
build:
runs-on: ${{ matrix.os }}-latest
strategy:
matrix:
os: [ubuntu, macos]
steps:
- uses: actions/checkout@v1
- name: Set up JDK
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: "Build"
run: ./gradlew nativeImage
- name: "Upload binaries"
uses: actions/[email protected]
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ github.event.release.upload_url }}
asset_path: build/graal/tester
asset_name: tester_${{ matrix.os }}
asset_content_type: application/octet-stream
Добавляем picocli
Добавляем зависимости:
annotationProcessor("info.picocli:picocli-codegen:4.4.0")
implementation("info.picocli:picocli:4.4.0")
Добавляем команду IssueGetCommand
:
@CommandLine.Command(
name = "issue-get", mixinStandardHelpOptions = true,
description = "Get information about Issue by number"
)
public class IssueGetCommand implements Runnable {
@CommandLine.Option(
names = {"--owner"},
description = "Repository owner"
)
protected String owner;
@CommandLine.Option(
names = {"--repo"},
description = "Repository name"
)
protected String repo;
@CommandLine.Option(
names = {"--number"},
description = "Issue number"
)
protected Integer number;
@Override
public void run() {
try {
runUnsafe();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
public void runUnsafe() throws Exception {
final GitHubService github = createRetrofit().create(GitHubService.class);
final Response<Issue> response = github.getIssue(owner, repo, number).execute();
if (response.isSuccessful()) {
final Issue issue = response.body();
System.out.println(String.format("#%d [%s] %s", issue.getNumber(), issue.getState(), issue.getTitle()));
} else {
System.out.println(response.errorBody().string());
}
}
}
Добавляем основную команду MainCommand
@CommandLine.Command(
name = "tester",
subcommands = {
IssueGetCommand.class
}
)
public class MainCommand implements Runnable {
@Override
public void run() {
new CommandLine(new MainCommand()).usage(System.out);
}
}
Изменяем класс Tester
:
public static void main(String[] args) {
final CommandLine cmd = new CommandLine(new MainCommand());
final CommandLine.ParseResult parseResult = cmd.parseArgs(args);
if (!parseResult.errors().isEmpty()) {
System.out.println(cmd.getUsageMessage());
}
int exitCode = cmd.execute(args);
System.exit(exitCode);
}
Добавляем команды List, Update
Создаем класс IssueListCommand
:
@CommandLine.Command(
name = "issue-list", mixinStandardHelpOptions = true,
description = "Get information about issues in repository"
)
public class IssueListCommand implements Runnable {
@CommandLine.Option(
names = {"--owner"},
description = "Repository owner"
)
protected String owner;
@CommandLine.Option(
names = {"--repo"},
description = "Repository name"
)
protected String repo;
@Override
public void run() {
try {
runUnsafe();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
public void runUnsafe() throws Exception {
final GitHubService github = createRetrofit().create(GitHubService.class);
final Response<List<Issue>> response = github.getIssues(owner, repo).execute();
if (response.isSuccessful()) {
response.body().forEach(issue -> {
System.out.println(String.format("#%d [%s] %s", issue.getNumber(), issue.getState(), issue.getTitle()));
});
} else {
System.out.println(response.errorBody().string());
}
}
}
Создаем класс IssueUpdateCommand
:
@CommandLine.Command(
name = "issue-update", mixinStandardHelpOptions = true,
description = "Update an issue by number"
)
public class IssueUpdateCommand implements Runnable {
@CommandLine.Option(
names = {"--owner"},
description = "Repository owner"
)
protected String owner;
@CommandLine.Option(
names = {"--repo"},
description = "Repository name"
)
protected String repo;
@CommandLine.Option(
names = {"--number"},
description = "Issue number"
)
protected int number;
@CommandLine.Option(
names = {"--title"},
description = "Issue title"
)
protected String title;
@CommandLine.Option(
names = {"--state"},
description = "Issue state"
)
protected String state;
@Override
public void run() {
try {
runUnsafe();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
public void runUnsafe() throws Exception {
final GitHubService github = createRetrofit().create(GitHubService.class);
final Response<Issue> issueResponse = github.getIssue(owner, repo, number).execute();
if (!issueResponse.isSuccessful()) {
System.out.println(issueResponse.errorBody().string());
}
final Issue patch = issueResponse.body();
Optional.ofNullable(title).ifPresent(patch::setTitle);
Optional.ofNullable(state).ifPresent(patch::setState);
final Response<Issue> updateResponse = github.updateIssue(owner, repo, number, patch).execute();
if (updateResponse.isSuccessful()) {
final Issue updated = updateResponse.body();
System.out.println(String.format("#%d [%s] %s", updated.getNumber(), updated.getState(), updated.getTitle()));
} else {
System.out.println(updateResponse.errorBody().string());
}
}
}
Добавляем команды в MainCommand
:
@CommandLine.Command(
name = "tester",
subcommands = {
IssueListCommand.class,
IssueGetCommand.class,
IssueUpdateCommand.class
}
)
Делаем сборку:
./gradlew clean nativeImage
Выполняем команды:
./build/graal/tester issue-list --owner eroshenkoam --repo allure-example
./build/graal/tester issue-update --owner eroshenkoam --repo allure-example --number 10 --title "Hello, Seva" --state "open"
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.