ATBTariffCalculator/CalculatorCInterface/git_library.cpp
2024-03-28 16:45:46 +01:00

94 lines
3.4 KiB
C++

#include "git_library.h"
#include "local_git_repository.h"
#include <QDir>
#include <QDebug>
#include <git2.h>
int GitLibrary::Init() {
return git_libgit2_init();
}
int GitLibrary::Shutdown() {
return git_libgit2_shutdown();
}
int GitLibrary::CheckoutRepository(char const *localRepoName, char const *branchName) {
QString localRepo(localRepoName);
QDir localRepoDir;
if (strstr(localRepoName, "customer_") == localRepoName) { // localRepoPath starts with 'customer_'
QString const &p = QDir::cleanPath(LocalGitRepository::GetReposRootDirectory()
+ QDir::separator() + localRepoName);
localRepoDir.setPath(p);
} else {
qCritical() << __func__ << ":" << __LINE__
<< "localRepoPath" << localRepoDir.path() << "either not absolute"
<< "or not starting with customer_*";
return -1;
}
}
int GitLibrary::CloneRepository(char const *url, char const *localRepoPath /* absolute path or repo-name */) {
QString localRepoName;
QDir localRepoDir;
if (strstr(localRepoPath, "customer_") == localRepoPath) { // localRepoPath starts with 'customer_'
QString const &p = QDir::cleanPath(LocalGitRepository::GetReposRootDirectory()
+ QDir::separator() + localRepoPath);
localRepoDir.setPath(p);
localRepoName = localRepoPath;
} else if (QDir::isAbsolutePath(localRepoPath) &&
strstr(localRepoPath, "/customer_") != localRepoPath) {
localRepoDir.setPath(localRepoPath);
localRepoName = localRepoDir.dirName(); // extract e.g. customer_999
} else {
qCritical() << __func__ << ":" << __LINE__
<< "localRepoPath" << localRepoPath << "either not absolute"
<< "or not starting with customer_*";
return -1;
}
if (!QDir(localRepoDir).exists()) {
if (!QDir().mkpath(localRepoDir.absolutePath())) {
qCritical() << __func__ << ":" << __LINE__
<< "can not create git-repositories-root-dir" << localRepoDir;
return -1;
}
}
QDir gitDir(QDir::cleanPath(localRepoDir.absolutePath() + QDir::separator() + ".git"));
if (gitDir.exists()) {
qCritical() << __func__ << ":" << __LINE__
<< "local repository" << gitDir.path() << "already exists,"
<< "no clone necessary";
return -1;
}
int res = 0;
QDir const &current = QDir::current();
git_clone_options opts;
if ((res = git_clone_options_init(&opts, GIT_CLONE_OPTIONS_VERSION)) == 0) {
opts.checkout_branch = "master";
if (QDir::setCurrent(localRepoDir.absolutePath())) {
git_repository *out = LocalGitRepository::GetInstance(localRepoName)->GetGitRepository();
if ((res = git_clone(&out, url, ".", &opts)) < 0) {
git_error const *error = git_error_last();
qCritical() << __func__ << ":" << __LINE__ << error->message << localRepoDir.absolutePath();
}
QDir::setCurrent(current.absolutePath());
} else {
qCritical() << __func__ << ":" << __LINE__
<< "ERROR setCurrent" << localRepoDir.absolutePath();
res = -1;
}
} else {
git_error const *error = git_error_last();
qCritical() << __func__ << ":" << __LINE__ << error->message;
}
return res;
}