GitTeaUtil.java 2.46 KB
Newer Older
Dominik Vayhinger's avatar
Dominik Vayhinger committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package de.hftstuttgart.utils;

import de.hftstuttgart.config.ModocotProperties;
import io.gitea.ApiClient;
import io.gitea.ApiException;
import io.gitea.Configuration;
import io.gitea.api.RepositoryApi;
import io.gitea.api.UserApi;
import io.gitea.auth.HttpBasicAuth;
import io.gitea.model.CreateRepoOption;
import io.gitea.model.Repository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class GitTeaUtil {

    private static final Logger LOG = LogManager.getLogger(GitTeaUtil.class);

    private final ModocotProperties modocotProperties;

    public GitTeaUtil(ModocotProperties modocotProperties) {
        this.modocotProperties = modocotProperties;
    }

    /**
     * Create Git-Repository with name {@code repositoryName} on internal Git-Server
     *
     * @param repositoryName name of new Repository
     * @return newly created Repository
     */
    public Repository createRepository(String repositoryName) {
        setupAuth();
        Repository repo = null;
        try {
            repo = new UserApi()
                    .createCurrentUserRepo(new CreateRepoOption().name(repositoryName));
        } catch (ApiException e) {
            LOG.error(String.format("Error while creating repository: %s", repositoryName), e);
        }
        if (repo != null) {
            LOG.info("Created repository {} on {}", repositoryName, repo.getCloneUrl());
        } else {
            throw new IllegalStateException("Repository is null");
        }
        return repo;
    }

    /**
     * Delete Git-Repository with name {@code repositoryName} on internal Git-Server
     *
     * @param repositoryName name of new Repository
     */
    public void deleteRepository(String repositoryName) {
        setupAuth();
        try {
            new RepositoryApi().repoDelete(this.modocotProperties.getGitTeaUsername(), repositoryName);
        } catch (ApiException e) {
            LOG.error("Error while deleting repository:" + e.getMessage());
        }
    }

    private void setupAuth() {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        defaultClient.setBasePath(this.modocotProperties.getGitTeaBasePath());
        HttpBasicAuth basicAuth = (HttpBasicAuth) defaultClient.getAuthentication("BasicAuth");
        basicAuth.setUsername(this.modocotProperties.getGitTeaUsername());
        basicAuth.setPassword(this.modocotProperties.getGitTeaPassword());
    }
}