1
0
mirror of https://github.com/QRouland/UTPass.git synced 2026-01-08 10:46:58 +00:00

Some GIT clone improvements (error messgages ...)

This commit is contained in:
2026-01-05 21:03:50 +01:00
parent 1fdc08eddf
commit 080906740c
15 changed files with 257 additions and 124 deletions

View File

@@ -6,6 +6,7 @@ set(
plugin.cpp
git.cpp
utils.h
error.h
jobs/clonejob.cpp
jobs/gitjob.cpp
)

54
plugins/Git/error.h Normal file
View File

@@ -0,0 +1,54 @@
// error.h
#ifndef ERROR_H
#define ERROR_H
#include <string>
extern "C" {
#include <git2.h>
}
// Enum for Git-specific errors (e.g., from git_clone)
enum class GitCloneErrorCode {
Successful = 0,
UnexpectedError, ///< Unknown or unexpected error
InvalidUrl, ///< Malformed URL error
NoUsername, ///< Missing username error
AuthentificationError, ///< Authentification error
UrlTypeDoNotMatchCreds,
};
/**
* Convert a git_error to a GitCloneErrorCode
* @param error A pointer to the git_error structure
* @return Corresponding GitCloneErrorCode integer value
*/
inline GitCloneErrorCode gitErrorToGitCloneErrorCode(const git_error* error) {
if (error == nullptr) {
return GitCloneErrorCode::Successful; ///< Default error if null
}
if (error->message != nullptr) {
if (std::string(error->message) == "malformed URL") {
return GitCloneErrorCode::InvalidUrl; ///< Invalid URL error
}
if (std::string(error->message) == "remote requested authentication but did not negotiate mechanisms") {
return GitCloneErrorCode::AuthentificationError; ///< Invalid URL error
}
}
return GitCloneErrorCode::UnexpectedError; ///< Default to UnexpectedError
}
/**
* Maps the given GitCloneErrorCode to its corresponding integer.
*
* @param error The GitCloneErrorCode value to convert.
* @return Corresponding GitCloneErrorCode integer value.
*/
constexpr int code_err(GitCloneErrorCode err)
{
return static_cast<int>(err);
}
#endif // ERROR_H

View File

@@ -1,3 +1,4 @@
#include "error.h"
#include <QUrl>
#include <QtCore/QDir>
#include <QDebug>
@@ -71,13 +72,13 @@ bool Git::cloneSshKey(QString url, QString path, QString passphrase)
return this->clone(url, path, mode);
}
void Git::cloneResult(const bool err)
void Git::cloneResult(const int err_code, const QString message)
{
if (err) {
emit cloneFailed(); // TODO error message
} else {
if (err_code == code_err(GitCloneErrorCode::Successful)) {
emit cloneSucceed();
} else {
emit cloneFailed(err_code, message);
}
this->m_sem->release();
}

View File

@@ -1,8 +1,8 @@
#ifndef GIT_H
#define GIT_H
#include "error.h"
#include "jobs/gitjob.h"
#include "qdebug.h"
#include <QUrl>
#include <QObject>
#include <QSemaphore>
@@ -28,10 +28,10 @@ private slots:
* process finishes. It emits the appropriate signal based on whether the clone operation succeeded
* or failed.
*
* @param err A boolean indicating whether an error occurred during cloning. `true` if the clone failed,
* `false` if it succeeded.
* @param err A err_code indicating whether an error occurred during cloning.
* @param err An error message.
*/
void cloneResult(const bool err);
void cloneResult(const int err_code, const QString message);
signals:
/**
@@ -44,9 +44,11 @@ signals:
/**
* @brief Signal emitted when the cloning operation fails.
*
* @param err_code The error code
* @param msg The deffautl error message from libgit
* This signal is emitted when an error occurs during the cloning operation.
*/
void cloneFailed();
void cloneFailed(int err_code, QString msg);
private:
std::unique_ptr<QSemaphore> m_sem; /**< Semaphore for managing concurrent operations. */

View File

@@ -3,12 +3,14 @@
#include <QUrl>
#include <QDebug>
#include <QObject>
#include <memory>
#include <type_traits>
extern "C" {
#include <git2.h>
}
#include "clonejob.h"
#include "../error.h"
CloneJob::CloneJob(QString url, QString path, cred_type cred):
GitJob(cred),
@@ -18,69 +20,90 @@ CloneJob::CloneJob(QString url, QString path, cred_type cred):
this->setObjectName("CloneJob");
}
void CloneJob::run()
{
auto tmp_dir = this->cloneSetup();
auto ret = this->clone(this->m_url, tmp_dir.absolutePath(), this->m_cred, this->credentialsCB);
if (ret) {
const auto [errorCode, errorMessage] = this->clone(m_url, tmp_dir.absolutePath(), this->m_cred, this->credentialsCB);
if (errorCode == GitCloneErrorCode::Successful) {
this->moveToDestination(tmp_dir, this->m_path);
}
this->cloneCleanUp(tmp_dir);
emit resultReady(!ret); // TODO Clean error handling to return specifics errors for the ui
emit resultReady(code_err(errorCode), errorMessage);
}
QDir CloneJob::cloneSetup()
{
QDir tmp_dir(QStandardPaths::writableLocation( QStandardPaths::CacheLocation).append("/clone"));
QDir tmp_dir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation).append("/clone"));
tmp_dir.removeRecursively();
qDebug() << "[CloneJob] Temp dir path is " << tmp_dir.absolutePath();
tmp_dir.removeRecursively(); // Clean the directory before use
qDebug() << "[CloneJob] Temp dir path is" << tmp_dir.absolutePath();
return tmp_dir;
}
bool CloneJob::cloneCleanUp(QDir tmp_dir)
{
return tmp_dir.removeRecursively();
if (!tmp_dir.removeRecursively()) {
qWarning() << "[CloneJob] Failed to clean up temporary directory:" << tmp_dir.absolutePath();
return false;
}
return true;
}
bool CloneJob::moveToDestination(QDir tmp_dir, QString path)
bool CloneJob::moveToDestination(QDir tmp_dir, const QString& path)
{
qDebug() << "[CloneJob] Removing password_store " << path;
qDebug() << "[CloneJob] Removing existing destination:" << path;
QDir destination_dir(path);
destination_dir.removeRecursively();
destination_dir.removeRecursively(); // Clean the destination directory
qDebug() << "[CloneJob] Moving cloned content to destination dir";
QDir dir;
qDebug() << "[CloneJob]" << tmp_dir.absolutePath() << " to " << destination_dir.absolutePath();
return dir.rename(tmp_dir.absolutePath(), destination_dir.absolutePath()); // TODO Better error handling
if (!QDir().rename(tmp_dir.absolutePath(), destination_dir.absolutePath())) {
qWarning() << "[CloneJob] Failed to move directory from" << tmp_dir.absolutePath() << "to" << destination_dir.absolutePath();
return false;
}
return true;
}
bool CloneJob::clone(QString url, QString path, cred_type cred, git_cred_acquire_cb cb)
const QPair<GitCloneErrorCode, QString> CloneJob::clone(QString url, QString path, cred_type cred, git_cred_acquire_cb cb)
{
git_repository *repo = NULL;
git_repository *repo = nullptr; // Use nullptr for type safety
git_clone_options opts = GIT_CLONE_OPTIONS_INIT;
PayloadCB payload = PayloadCB(false, cred);
PayloadCB payload(false, cred);
opts.fetch_opts.callbacks.credentials = cb;
opts.fetch_opts.callbacks.payload = &payload;
int ret = git_clone(&repo, url.toLocal8Bit().data(), path.toLocal8Bit().data(), &opts);
if (ret == GIT_EUSER ) {
qDebug() << "[CloneJob] CallBack Error";
} else if (ret != 0) {
auto err = git_error_last(); // TODO Better error handling for return ui messages
if (err) {
qDebug() << "[CloneJob]" << git_error_last()->message;
}
// Map the application specific cb errors if any
if (ret == GIT_EUSER) {
if(payload.err == ErrorCodeCB::NoUsername)
return {GitCloneErrorCode::NoUsername, "no username provided in URL"};
if(payload.err == ErrorCodeCB::InvalidCreds)
return {GitCloneErrorCode::AuthentificationError, "authentification error"};
if(payload.err == ErrorCodeCB::UrlTypeDoNotMatchCreds)
return {GitCloneErrorCode::UrlTypeDoNotMatchCreds, "invalid creds types for provided url"};
return {GitCloneErrorCode::UnexpectedError, "unexcepted error occured"};
}
const git_error* err = git_error_last(); // Retrieve the last error git error
// Log error details for debugging
if (err) {
qDebug() << "[CloneJob] Error class:" << err->klass;
qDebug() << "[CloneJob] Error message:" << err->message;
}
// Check if the repository was successfully created and free it
if (repo) {
git_repository_free(repo);
}
return ret == 0;
}
// Return the error code mapped from git_error_last
return { gitErrorToGitCloneErrorCode(err), err ? QString::fromUtf8(err->message) : "success"};
}

View File

@@ -6,6 +6,7 @@ extern "C" {
#include <git2.h>
}
#include "gitjob.h"
#include "../error.h"
/**
* @class CloneJob
@@ -26,14 +27,13 @@ class CloneJob : public GitJob
signals:
/**
* @brief Signal emitted when the cloning operation is complete.
*
* This signal is emitted once the cloning operation finishes.
*
* @param err A boolean indicating whether an error occurred during cloning.
* `true` if an error occurred, `false` if the clone was successful.
*/
void resultReady(const bool err);
* @brief Signal emitted when the cloning operation is complete.
*
* This signal is emitted once the cloning operation finishes.
*
* @param err A Git error.
*/
void resultReady(const int err_code, const QString message);
private:
QString m_url; ///< The URL of the Git repository to clone.
@@ -58,7 +58,7 @@ private:
* @param tmp_dir The temporary directory where the repository was cloned.
* @return `true` if the move was successful, `false` otherwise.
*/
static bool moveToDestination(QDir tmp_dir, QString path);
static bool moveToDestination(QDir tmp_dir, const QString& path);
/**
* @brief Tears down the temporary directory after cloning.
@@ -84,9 +84,10 @@ private:
* @param path The destination path for the cloned repository.
* @param cred The credentials to use for the cloning operation.
* @param cb The callback function for acquiring credentials during cloning.
* @return `true` if the cloning process was successful, `false` otherwise.
* @return A Git error, result of the operation.
*/
static bool clone(QString url, QString path, cred_type cred, git_cred_acquire_cb cb);
static const QPair<GitCloneErrorCode, QString> clone(QString url, QString path, cred_type cred, git_cred_acquire_cb cb);
public:
/**

View File

@@ -28,11 +28,13 @@ int GitJob::credentialsCB(git_cred **out, const char *url, const char *username_
if (!username_from_url) { // we required here that the username must be provided directly in url (maybe improve later on)
qWarning() << "[GitJob] credentials_cb : no username provided";
p->err = ErrorCodeCB::NoUsername;
return (int) GIT_EUSER;
}
if (p->called) {
qWarning() << "[GitJob] credentials_cb : cb already called, probably invalid creds";
p->err = ErrorCodeCB::InvalidCreds;
return (int) GIT_EUSER;
}
p->called = true;
@@ -45,26 +47,24 @@ int GitJob::credentialsCB(git_cred **out, const char *url, const char *username_
qWarning() << "[GitJob] credentialsCB : callback should never be call for HTTP";
return (int) GIT_EUSER;
},
[allowed_types, &out, &username_from_url](const HTTPUserPass & x)
[allowed_types, &out, &username_from_url, &p](const HTTPUserPass & x)
{
qDebug() << "[GitJob] credentialsCB : HTTPUserPass ";
if (!(allowed_types & GIT_CREDTYPE_USERPASS_PLAINTEXT)) {
qWarning() << "[GitJob] credentials_cb : allowed_types is invalid for HTTPUserPass creds";
p->err = ErrorCodeCB::UrlTypeDoNotMatchCreds;
return (int) GIT_EUSER;
}
return git_cred_userpass_plaintext_new(out, username_from_url, x.pass.toLocal8Bit().constData());
},
[allowed_types, &out, &username_from_url](const SSHKey & x)
[allowed_types, &out, &username_from_url , &p](const SSHKey & x)
{
qDebug() << "[GitJob] credentialsCB : SSHKey ";
if (!(allowed_types & GIT_CREDTYPE_SSH_KEY)) {
qWarning() << "[GitJob] credentials_cb : allowed_types is invalid for SSHKey creds";
p->err = ErrorCodeCB::UrlTypeDoNotMatchCreds;
return (int) GIT_EUSER;
}
qDebug() << "[GitJob] username_from_url :" << username_from_url;
qDebug() << "[GitJob] pub_key :" << x.pub_key.toLocal8Bit().constData();
qDebug() << "[GitJob] priv_key :" << x.priv_key.toLocal8Bit().constData();
qDebug() << "[GitJob] passphrase :" << x.passphrase.toLocal8Bit().constData();
return git_cred_ssh_key_new(out, username_from_url, x.pub_key.toLocal8Bit().constData(),
x.priv_key.toLocal8Bit().constData(), x.passphrase.toLocal8Bit().constData());
}

View File

@@ -31,12 +31,20 @@ struct SSHKey {
*/
typedef std::variant<HTTP, HTTPUserPass, SSHKey> cred_type;
enum class ErrorCodeCB {
None = 0,
NoUsername,
UrlTypeDoNotMatchCreds,
InvalidCreds,
};
struct PayloadCB
{
bool called;
cred_type creds;
PayloadCB(bool ca, cred_type cr): called(ca), creds(cr) {}
ErrorCodeCB err;
PayloadCB(bool ca, cred_type cr): called(ca), creds(cr), err(ErrorCodeCB::None) {}
};
/**

View File

@@ -1,7 +1,7 @@
#ifndef UTILS_H
#define UTILS_H
#define UNUSED(x) (void)(x)
#define UNUSED(x) (void)(x) // Stub used to hide some warnings
/**
* @brief A utility structure for enabling function overloading with template-based classes.