Merge pull request #114 from ChronicallySerious/gdextension-port

This commit is contained in:
Twarit Waikar
2022-08-31 23:58:26 +05:30
committed by GitHub
34 changed files with 263690 additions and 213116 deletions

View File

@@ -11,11 +11,11 @@ jobs:
run: |
git submodule update --init --recursive
pip3 install --user scons
scons platform=linux target=release bits=64 godot_cpp=yes generate_bindings=yes use_custom_api_file=yes custom_api_file=api.ci.json -j $(nproc)
ldd demo/addons/godot-git-plugin/linux/libgitapi.so
scons platform=linux target=release bits=64 godot_cpp=yes generate_bindings=yes use_custom_api_file=yes custom_api_file=extension_api.ci.json -j $(nproc)
ldd demo/addons/godot-git-plugin/linux/*.so
- uses: actions/upload-artifact@v2
with:
name: godot-git-plugin-linux-release-x64-${{ github.sha }}
name: libgit_plugin.linux.x86_64.release.dll-${{ github.sha }}
if-no-files-found: error
path: |
demo/
@@ -33,11 +33,11 @@ jobs:
run: |
git submodule update --init --recursive
pip3 install --user scons
scons platform=windows target=release bits=64 godot_cpp=yes generate_bindings=yes use_custom_api_file=yes custom_api_file=api.ci.json -j $env:NUMBER_OF_PROCESSORS
dumpbin /dependents .\demo\addons\godot-git-plugin\win64\libgitapi.dll
scons platform=windows target=release bits=64 godot_cpp=yes generate_bindings=yes use_custom_api_file=yes custom_api_file=extension_api.ci.json -j $env:NUMBER_OF_PROCESSORS
dumpbin /dependents .\demo\addons\godot-git-plugin\win64\*.dll
- uses: actions/upload-artifact@v2
with:
name: godot-git-plugin-windows-release-x64-${{ github.sha }}
name: libgit_plugin.windows.x86_64.release.dll-${{ github.sha }}
if-no-files-found: error
path: |
demo/
@@ -50,11 +50,11 @@ jobs:
run: |
git submodule update --init --recursive
brew install scons
scons platform=osx target=release bits=64 godot_cpp=yes generate_bindings=yes use_custom_api_file=yes custom_api_file=api.ci.json macos_arch=universal use_llvm=yes -j $(sysctl -n hw.logicalcpu)
otool -L demo/addons/godot-git-plugin/osx/libgitapi.dylib
scons platform=macos target=release bits=64 godot_cpp=yes generate_bindings=yes use_custom_api_file=yes custom_api_file=extension_api.ci.json macos_arch=universal use_llvm=yes -j $(sysctl -n hw.logicalcpu)
otool -L demo/addons/godot-git-plugin/macos/*.dylib
- uses: actions/upload-artifact@v2
with:
name: godot-git-plugin-macos-release-x64-${{ github.sha }}
name: libgit_plugin.macos.x86_64.release.dylib-${{ github.sha }}
if-no-files-found: error
path: |
demo/

7
.gitignore vendored
View File

@@ -1,8 +1,11 @@
# SConstruct db
*.dblite
# Godot ignores
demo/.godot/
# Godot Serialisations
api.json
extension_api.json
# Visual Studio Cache
.vs/
@@ -16,7 +19,7 @@ api.json
# Binaries
build/
bin/
osx/
macos/
linux/
win64/
*.lib

View File

@@ -26,29 +26,37 @@ This section onwards is only meant to be used if you intend to compile the plugi
- Windows
- No extra steps required other than setting up the compilers.
- MacOS
- For making universal builds targeting both Apple Silicon and x86_64, you can optionally run `build_openssl_universal_osx.sh` to build OpenSSL yourself and replace the already prebuilt libraries provided inside `thirdparty/openssl/`, otherwise, just run `brew install openssl@1.1`.
- For making universal builds targeting both Apple Silicon and x86_64, you can optionally run `build_openssl_universal_macos.sh` to build OpenSSL yourself and replace the already prebuilt libraries provided inside `thirdparty/openssl/`, otherwise, just run `brew install openssl@1.1` to use the prebuilt libraries provided in this repository.
- Linux
- Run `sudo apt-get install libssl-dev`, or local package manager equivalent.
- Run `sudo apt-get install libssl-dev`, or your local package manager's equivalent.
### Build
### Release Build
```
scons platform=<platform> target=release bits=64 -j 6
scons platform=<platform> target=release -j 6
```
For more build options, run `scons platform=<platform> -h`
## Bleeding Edge
## Dev builds
Most of the times when new features are being worked on for the Godot VCS Integration, it requires developers to make changes in the Godot Editor source code along with this plugin. This means we need to manually generate the GDNative API from the custom Godot builds and then use it to compile godot-cpp.
When new features are being worked on for the Godot VCS Integration, the build process sometimes requires developers to make changes in the GDExtension API along with this plugin. This means we need to manually generate the GDExtension API from the custom Godot builds and then use it to compile godot-cpp.
To build using custom GDNative API definition JSON files, run the below helper command:
If you need to use a custom GDExtension API:
```
scons platform=<platform> target=debug godot_cpp=yes generate_bindings=yes bits=64 use_custom_api_file=yes custom_api_file=path/to/api.json -j 6
scons platform=<platform> target=debug godot_cpp=yes generate_bindings=yes bits=64 use_custom_api_file=yes custom_api_file=path/to/extension_api.json -j 6
```
Once this command is completed successfully, the standard build commands in the above section can be run without recompiling godot-cpp. Once compiled, to stop godot-cpp from recompiling, do not use the `godot_cpp` option in SCons arguments. To view more options available while recompiling godot-cpp, run `scons platform=<platform> godot_cpp=yes -h`.
You only need to build godot-cpp once every change in the GDExtension API, hence, this command should only be run the first time after generating a new JSON API file.
To reuse the once-built godot-cpp library:
```
scons platform=<platform> target=debug -j 6
```
To view more options available while recompiling godot-cpp, run `scons platform=<platform> godot_cpp=yes -h`.
---

View File

@@ -13,9 +13,9 @@ env = Environment(ENV=os.environ)
opts.Add(EnumVariable("target", "Compilation target",
"debug", ["d", "debug", "r", "release"]))
opts.Add(EnumVariable("platform", "Compilation platform",
"", ["", "windows", "linux", "osx"]))
"", ["", "windows", "linux", "macos"]))
opts.Add(EnumVariable("p", "Compilation target, alias for \"platform\"",
"", ["", "windows", "linux", "osx"]))
"", ["", "windows", "linux", "macos"]))
opts.Add(BoolVariable(
"godot_cpp", "Build godot-cpp by forwarding arguments to it.", "no"))
opts.Add(BoolVariable("use_llvm",
@@ -23,7 +23,7 @@ opts.Add(BoolVariable("use_llvm",
opts.Add(PathVariable("target_path",
"The path where the lib is installed.", "demo/addons/godot-git-plugin/"))
opts.Add(PathVariable("target_name", "The library name.",
"libgitapi", PathVariable.PathAccept))
"libgit_plugin", PathVariable.PathAccept))
opts.Add(EnumVariable("bits", "The bit architecture.", "64", ["64"]))
opts.Add(EnumVariable("macos_arch", "Target macOS architecture",
"universal", ["universal", "x86_64", "arm64"]))
@@ -37,8 +37,11 @@ opts.Add(PathVariable("macos_openssl_static_crypto", "Path to OpenSSL libcrypto.
# Updates the environment with the option variables.
opts.Update(env)
if env["platform"] == "osx":
# Use only clang on osx because we need to do universal builds
if env["p"] != "":
env["platform"] = env["p"]
if env["platform"] == "macos":
# Use only clang on macos because we need to do universal builds
env["CXX"] = "clang++"
env["CC"] = "clang"
@@ -54,7 +57,7 @@ Export("env")
SConscript("thirdparty/SCsub")
if env["godot_cpp"]:
if ARGUMENTS.get("use_custom_api_file", False) and ARGUMENTS.get("custom_api_file", "") != "":
if ARGUMENTS.get("custom_api_file", "") != "":
ARGUMENTS["custom_api_file"] = "../" + ARGUMENTS["custom_api_file"]
SConscript("godot-cpp/SConstruct")

View File

@@ -2,7 +2,7 @@
The Godot Git Plugin source code uses the following third-party source code:
1. godotengine/godot-cpp - MIT License - https://github.com/godotengine/godot-cpp/tree/99e9dd1d9396ed3af40678263b509078e5265ffc
1. godotengine/godot-cpp - MIT License - https://github.com/godotengine/godot-cpp/tree/8ba1c059da5e97428d40612dd0afc2be4079b5c6
2. libgit2/libgit2 - GPLv2 with a special Linking Exception - https://github.com/libgit2/libgit2/tree/b7bad55e4bb0a285b073ba5e02b01d3f522fc95d
3. libssh2/libssh2 - BSD-3-Clause License - https://github.com/libssh2/libssh2/tree/635caa90787220ac3773c1d5ba11f1236c22eae8
@@ -17,7 +17,7 @@ We also link to these third-party libraries (only in the compiled binary form):
```
# MIT License
Copyright (c) 2017-2021 Godot Engine contributors.
Copyright (c) 2017-2022 Godot Engine contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

212598
api.ci.json

File diff suppressed because it is too large Load Diff

13
demo/.gitignore vendored
View File

@@ -1,11 +1,2 @@
# Godot-specific ignores
.import/
export.cfg
export_presets.cfg
# Imported translations (automatically generated from CSV files)
*.translation
# Mono-specific ignores
.mono/
data_*/
# Godot 4+ specific ignores
.godot/

View File

@@ -1,18 +0,0 @@
[general]
load_once=true
symbol_prefix="godot_"
reloadable=false
singleton=false
[entry]
OSX.64="res://addons/godot-git-plugin/osx/libgitapi.dylib"
Windows.64="res://addons/godot-git-plugin/win64/libgitapi.dll"
X11.64="res://addons/godot-git-plugin/linux/libgitapi.so"
[dependencies]
OSX.64=[ ]
Windows.64=[ ]
X11.64=[ ]

View File

@@ -1,9 +0,0 @@
[gd_resource type="NativeScript" load_steps=2 format=2]
[ext_resource path="res://addons/godot-git-plugin/git_api.gdnlib" type="GDNativeLibrary" id=1]
[resource]
resource_name = "GitAPI"
class_name = "GitAPI"
library = ExtResource( 1 )
script_class_name = "GitAPI"

View File

@@ -0,0 +1,16 @@
[configuration]
entry_symbol = "git_plugin_init"
[libraries]
macos.debug = "macos/libgit_plugin.macos.universal.debug.dylib"
macos.release = "macos/libgit_plugin.macos.universal.release.dylib"
windows.debug.x86_64 = "win64/libgit_plugin.windows.x86_64.debug.dll"
windows.release.x86_64 = "win64/libgit_plugin.windows.x86_64.release.dll"
linux.debug.x86_64 = "linux/libgit_plugin.linux.x86_64.debug.so"
linux.release.x86_64 = "linux/libgit_plugin.linux.x86_64.release.so"
linux.debug.arm64 = "linux/libgit_plugin.linux.arm64.debug.so"
linux.release.arm64 = "linux/libgit_plugin.linux.arm64.release.so"
linux.debug.rv64 = ""
linux.release.rv64 = ""

View File

@@ -3,5 +3,5 @@
name="Godot Git Plugin"
description="This plugin lets you interact with Git without leaving the Godot editor. More information can be found at https://github.com/godotengine/godot-git-plugin/wiki"
author="ChronicallySerious"
version="v2.0.0"
script="git_api.gdns"
version="v3.0.0"
script="git_plugin.gdns"

View File

@@ -1,7 +0,0 @@
[gd_resource type="Environment" load_steps=2 format=2]
[sub_resource type="ProceduralSky" id=1]
[resource]
background_mode = 2
background_sky = SubResource( 1 )

View File

@@ -1,3 +1,3 @@
[gd_scene format=2]
[gd_scene format=3 uid="uid://cr5ci1iwmxnlb"]
[node name="Node2D" type="Node2D"]
[node name="Node3D" type="Node3D"]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

View File

@@ -1,35 +0,0 @@
[remap]
importer="texture"
type="StreamTexture"
path="res://.import/icon.png-487276ed1e3a0c39cad0279d744ee560.stex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://icon.png"
dest_files=[ "res://.import/icon.png-487276ed1e3a0c39cad0279d744ee560.stex" ]
[params]
compress/mode=0
compress/lossy_quality=0.7
compress/hdr_mode=0
compress/bptc_ldr=0
compress/normal_map=0
flags/repeat=0
flags/filter=true
flags/mipmaps=false
flags/anisotropic=false
flags/srgb=2
process/fix_alpha_border=true
process/premult_alpha=false
process/HDR_as_SRGB=false
process/invert_color=false
process/normal_map_invert_y=false
stream=false
size_limit=0
detect_3d=true
svg/scale=1.0

View File

@@ -1,16 +1,12 @@
extends Node
# Declare member variables here. Examples:
# var a = 2
# var b = "text"
# Called when the node enters the scene tree for the first time.
func _ready():
print("Hello Godot!")
print("Hello world!")
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
# pass
func _process(delta):
pass

View File

@@ -6,29 +6,13 @@
; [section] ; section goes between []
; param=value ; assign values to parameters
config_version=4
_global_script_classes=[ {
"base": "EditorVCSInterface",
"class": "GitAPI",
"language": "NativeScript",
"path": "res://addons/godot-git-plugin/git_api.gdns"
} ]
_global_script_class_icons={
"GitAPI": ""
}
config_version=5
[application]
config/name="demo"
run/main_scene="res://demo.tscn"
config/icon="res://icon.png"
config/features=PackedStringArray("4.0")
[editor]
version_control/plugin_name="GitPlugin"
version_control/autoload_on_startup=true
version_control/plugin_name="GitAPI"
[rendering]
environment/default_environment="res://default_env.tres"

263248
extension_api.ci.json Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -8,29 +8,32 @@ Import("env")
godot_headers_path = "../godot-cpp/godot-headers/"
cpp_bindings_path = "../godot-cpp/"
cpp_library = "libgodot-cpp"
bits = env["bits"]
target_arch = ""
dynamic_lib_extension = ""
# Process some arguments
if env["use_llvm"]:
env["CC"] = "clang"
env["CXX"] = "clang++"
if env["p"] != "":
env["platform"] = env["p"]
if env["platform"] == "":
print("No valid target platform selected.")
quit()
if env["bits"] == "64":
target_arch = "x86_64"
env["target_path"] = "../" + env["target_path"]
if not os.path.isdir(env["target_path"]):
os.mkdir(env["target_path"])
# Check our platform specifics
if env["platform"] == "osx":
env["target_path"] += "osx/"
cpp_library += ".osx"
if env["platform"] == "macos":
env["target_path"] += "macos/"
cpp_library += ".macos"
dynamic_lib_extension = "dylib"
target_arch = env["macos_arch"]
# Force static linkage (https://stackoverflow.com/a/2995999/7370948)
static_ssl = File(env["macos_openssl_static_ssl"])
@@ -46,6 +49,7 @@ elif env["platform"] == "linux":
env["target_path"] += "linux/"
cpp_library += ".linux"
env.Append(LIBS=["ssl", "crypto"])
dynamic_lib_extension = "so"
if env["target"] in ("debug", "d"):
env.Append(CCFLAGS=["-fPIC", "-g3", "-Og", "-std=c++17"])
@@ -53,11 +57,14 @@ elif env["platform"] == "linux":
env.Append(CCFLAGS=["-fPIC", "-g", "-O3", "-std=c++17"])
elif env["platform"] == "windows":
# TODO: Make this only apply when using MSVC
env.Append(CPPDEFINES=["TYPED_METHOD_BIND"])
env["target_path"] += "win64/"
cpp_library += ".windows"
# This makes sure to keep the session environment variables on windows,
# that way you can run scons in a vs 2017 prompt and it will find all the required tools
env.Append(ENV=os.environ)
dynamic_lib_extension = "dll"
env.Append(CCFLAGS=["-DWIN32", "-D_WIN32", "-D_WINDOWS",
"-W3", "-GR", "-D_CRT_SECURE_NO_WARNINGS", "/std:c++17"])
@@ -74,19 +81,22 @@ if env["target"] in ("debug", "d"):
else:
cpp_library += ".release"
if env['platform'] == 'osx' and env['macos_arch'] != 'universal':
cpp_library += "." + env['macos_arch']
else:
cpp_library += "." + str(bits)
cpp_library += "." + target_arch
env.Append(CPPPATH=[".", "src/"])
env.Append(CPPPATH=[godot_headers_path, cpp_bindings_path + "include/",
cpp_bindings_path + "include/core/", cpp_bindings_path + "include/gen/"])
env.Append(CPPPATH=[
godot_headers_path,
cpp_bindings_path + "include/",
cpp_bindings_path + "gen/include/"
])
env.Append(CPPPATH=["../thirdparty/git2/libgit2/include/"])
env.Append(LIBPATH=[cpp_bindings_path + "bin/", "../thirdparty/bin/"])
env.Prepend(LIBS=[cpp_library, "git2", "ssh2"])
library = env.SharedLibrary(
target=env["target_path"] + env["target_name"],
target=env["target_path"] + env["target_name"] + "." +
env["platform"] + "." + target_arch + "." +
env["target"] + "." + dynamic_lib_extension,
source=Glob("src/*.cpp"))
Default(library)

View File

@@ -1,7 +0,0 @@
#ifndef ALLOCATION_DEF_H
#define ALLOCATION_DEF_H
#define memnew(klass) new klass()
#define memdelete(pointer) pointer ? delete pointer : WARN_PRINT("GitAPI: Tried to delete a NULL object");
#endif // !ALLOCATION_DEF_H

View File

@@ -1,20 +1,31 @@
#include "git_api.h"
#include "git_plugin.h"
#include <Godot.hpp>
#include "godot_cpp/core/class_db.hpp"
#include "godot_cpp/godot.hpp"
extern "C" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *o) {
godot::Godot::gdnative_init(o);
void initialize_git_plugin_module(godot::ModuleInitializationLevel p_level) {
if (p_level != godot::MODULE_INITIALIZATION_LEVEL_EDITOR) {
return;
}
godot::ClassDB::register_class<GitPlugin>();
}
extern "C" void GDN_EXPORT godot_gdnative_singleton(godot_gdnative_init_options *o) {
void uninitialize_git_plugin_module(godot::ModuleInitializationLevel p_level) {
if (p_level != godot::MODULE_INITIALIZATION_LEVEL_EDITOR) {
return;
}
}
extern "C" void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *o) {
godot::Godot::gdnative_terminate(o);
}
extern "C" {
extern "C" void GDN_EXPORT godot_nativescript_init(void *handle) {
godot::Godot::nativescript_init(handle);
GDNativeBool GDN_EXPORT git_plugin_init(const GDNativeInterface *p_interface, const GDNativeExtensionClassLibraryPtr p_library, GDNativeInitialization *r_initialization) {
godot::GDExtensionBinding::InitObject init_obj(p_interface, p_library, r_initialization);
godot::register_tool_class<godot::GitAPI>();
init_obj.register_initializer(initialize_git_plugin_module);
init_obj.register_terminator(uninitialize_git_plugin_module);
init_obj.set_minimum_library_initialization_level(godot::MODULE_INITIALIZATION_LEVEL_EDITOR);
return init_obj.init();
}
}

View File

@@ -1,152 +0,0 @@
#ifndef GIT_API_H
#define GIT_API_H
#include <memory>
#include <vector>
#include <GodotGlobal.hpp>
#include <AcceptDialog.hpp>
#include <Button.hpp>
#include <Control.hpp>
#include <Directory.hpp>
#include <EditorVCSInterface.hpp>
#include <File.hpp>
#include <Godot.hpp>
#include <LineEdit.hpp>
#include <OS.hpp>
#include <allocation_defs.h>
#include <git_common.h>
#include <git2.h>
namespace godot {
class GitAPI;
struct DiffHelper {
Array *diff_hunks;
GitAPI *git_api;
};
struct CString {
char *data = nullptr;
CString() = delete;
CString(const String &string) :
data(string.alloc_c_string()) {}
CString(CString &&) = delete;
CString &operator=(const CString &) = delete;
CString &operator=(CString &&) = delete;
~CString() {
if (data) {
godot::api->godot_free(data);
data = nullptr;
}
}
};
template <class T>
class Capture {
T &smart_ptr = nullptr;
using Raw = decltype(smart_ptr.get());
Raw raw = nullptr;
public:
Capture() = delete;
Capture(T &ptr) :
smart_ptr(ptr) {}
Capture(Capture &&) = delete;
Capture &operator=(const Capture &) = delete;
Capture &operator=(Capture &&) = delete;
operator Raw *() {
return &raw;
}
~Capture() {
if (raw) {
smart_ptr.reset(raw);
}
}
};
template <auto DeleteFn>
struct FunctionDeleter {
template <class T>
void operator()(T *ptr) {
DeleteFn(ptr);
}
};
template <class T, auto DeleteFn>
using unique_ptr_deleter = std::unique_ptr<T, FunctionDeleter<DeleteFn>>;
using git_annotated_commit_ptr = unique_ptr_deleter<git_annotated_commit, git_annotated_commit_free>;
using git_blob_ptr = unique_ptr_deleter<git_blob, git_blob_free>;
using git_branch_iterator_ptr = unique_ptr_deleter<git_branch_iterator, git_branch_iterator_free>;
using git_commit_ptr = unique_ptr_deleter<git_commit, git_commit_free>;
using git_diff_ptr = unique_ptr_deleter<git_diff, git_diff_free>;
using git_index_ptr = unique_ptr_deleter<git_index, git_index_free>;
using git_object_ptr = unique_ptr_deleter<git_object, git_object_free>;
using git_patch_ptr = unique_ptr_deleter<git_patch, git_patch_free>;
using git_reference_ptr = unique_ptr_deleter<git_reference, git_reference_free>;
using git_remote_ptr = unique_ptr_deleter<git_remote, git_remote_free>;
using git_repository_ptr = unique_ptr_deleter<git_repository, git_repository_free>;
using git_revwalk_ptr = unique_ptr_deleter<git_revwalk, git_revwalk_free>;
using git_signature_ptr = unique_ptr_deleter<git_signature, git_signature_free>;
using git_status_list_ptr = unique_ptr_deleter<git_status_list, git_status_list_free>;
using git_tree_ptr = unique_ptr_deleter<git_tree, git_tree_free>;
class GitAPI : public EditorVCSInterface {
GODOT_CLASS(GitAPI, EditorVCSInterface)
Credentials creds;
bool has_merge = false;
git_repository_ptr repo;
git_oid pull_merge_oid = {};
// Endpoints
bool _checkout_branch(const String branch_name);
void _commit(const String msg);
void _create_branch(const String branch_name);
void _create_remote(const String remote_name, const String remote_url);
void _discard_file(const String file_path);
void _fetch(const String remote);
Array _get_branch_list();
String _get_current_branch_name();
Array _get_diff(const String identifier, const int64_t area);
Array _get_line_diff(const String file_path, const String text);
Array _get_modified_files_data();
Array _get_previous_commits(const int64_t max_commits);
Array _get_remotes();
String _get_vcs_name();
bool _initialize(const String project_path);
void _pull(const String remote);
void _push(const String remote, const bool force);
void _remove_branch(const String branch_name);
void _remove_remote(const String remote_name);
void _set_credentials(const String username, const String password, const String ssh_public_key_path, const String ssh_private_key_path, const String ssh_passphrase);
bool _shut_down();
void _stage_file(const String file_path);
void _unstage_file(const String file_path);
// Helpers
Array _parse_diff(git_diff *p_diff);
public:
static void _register_methods();
bool check_errors(int error, String function, String file, int line, String message, const std::vector<git_error_code> &ignores = {});
void create_gitignore_and_gitattributes();
bool create_initial_commit();
void _init();
};
} // namespace godot
#endif // !GIT_API_H

View File

@@ -1,14 +1,18 @@
#include <git_common.h>
#include <iostream>
#include <cstring>
#include <git_api.h>
#include "git_callbacks.h"
#include "godot_cpp/godot.hpp"
#include "git_plugin.h"
extern "C" int progress_cb(const char *str, int len, void *data) {
(void)data;
char *progress_str = new char[len + 1];
memcpy(progress_str, str, len);
std::memcpy(progress_str, str, len);
progress_str[len] = '\0';
godot::Godot::print("remote: " + godot::String(progress_str).strip_edges());
std::cout << "remote: " << CString(godot::String(progress_str).strip_edges()).data << std::endl;
delete[] progress_str;
return 0;
@@ -22,10 +26,10 @@ extern "C" int update_cb(const char *refname, const git_oid *a, const git_oid *b
git_oid_tostr(b_str, short_commit_length, b);
if (git_oid_is_zero(a)) {
godot::Godot::print("* [new] " + godot::String(b_str) + " " + godot::String(refname));
std::cout << "* [new] " << CString(godot::String(b_str)).data << " " << CString(godot::String(refname)).data << std::endl;
} else {
git_oid_tostr(a_str, short_commit_length, a);
godot::Godot::print("[updated] " + godot::String(a_str) + "..." + godot::String(b_str) + " " + godot::String(refname));
std::cout << "[updated] " << CString(godot::String(a_str)).data << "..." << CString(godot::String(b_str)).data << " " << CString(godot::String(refname)).data << std::endl;
}
return 0;
@@ -35,9 +39,9 @@ extern "C" int transfer_progress_cb(const git_indexer_progress *stats, void *pay
(void)payload;
if (stats->received_objects == stats->total_objects) {
godot::Godot::print("Resolving deltas " + godot::String::num_int64(stats->indexed_deltas) + "/" + godot::String::num_int64(stats->total_deltas));
printf("Resolving deltas %d/%d\n", stats->indexed_deltas, stats->total_deltas);
} else if (stats->total_objects > 0) {
godot::Godot::print("Received " + godot::String::num_int64(stats->received_objects) + "/" + godot::String::num_int64(stats->total_objects) + " objects (" + godot::String::num_int64(stats->indexed_objects) + ") in " + godot::String::num_int64(static_cast<int>(stats->received_bytes)) + " bytes");
printf("Received %d/%d objects (%d) in %zu bytes\n", stats->received_objects, stats->total_objects, stats->indexed_objects, stats->received_bytes);
}
return 0;
}
@@ -56,18 +60,19 @@ extern "C" int push_transfer_progress_cb(unsigned int current, unsigned int tota
progress = (current * 100) / total;
}
godot::Godot::print("Writing Objects: " +
godot::String::num_int64(progress) + "% (" +
godot::String::num_int64((int)current) + "/" + godot::String::num_int64((int)total) + "), " + godot::String::num_int64(bytes) + " bytes, done.");
std::cout << "Writing Objects: "
<< progress << "% (" << current << "/" << total << ", "
<< bytes << " bytes done."
<< std::endl;
return 0;
}
extern "C" int push_update_reference_cb(const char *refname, const char *status, void *data) {
godot::String status_str = status;
if (status_str == "") {
godot::Godot::print("[rejected] " + godot::String(refname) + " " + status_str);
std::cout << "[rejected] " << CString(godot::String(refname)).data << " " << CString(status_str).data << std::endl;
} else {
godot::Godot::print("[updated] " + godot::String(refname));
std::cout << "[updated] " << CString(godot::String(refname)).data << std::endl;
}
return 0;
}
@@ -78,29 +83,29 @@ extern "C" int credentials_cb(git_cred **out, const char *url, const char *usern
godot::String proper_username = username_from_url ? username_from_url : creds->username;
if (allowed_types & GIT_CREDENTIAL_USERPASS_PLAINTEXT) {
return git_cred_userpass_plaintext_new(out, godot::CString(proper_username).data, godot::CString(creds->password).data);
return git_cred_userpass_plaintext_new(out, CString(proper_username).data, CString(creds->password).data);
}
if (allowed_types & GIT_CREDENTIAL_SSH_KEY) {
return git_credential_ssh_key_new(out,
godot::CString(proper_username).data,
godot::CString(creds->ssh_public_key_path).data,
godot::CString(creds->ssh_private_key_path).data,
godot::CString(creds->ssh_passphrase).data);
CString(proper_username).data,
CString(creds->ssh_public_key_path).data,
CString(creds->ssh_private_key_path).data,
CString(creds->ssh_passphrase).data);
}
if (allowed_types & GIT_CREDENTIAL_USERNAME) {
return git_credential_username_new(out, godot::CString(proper_username).data);
return git_credential_username_new(out, CString(proper_username).data);
}
return GIT_EUSER;
}
extern "C" int diff_hunk_cb(const git_diff_delta *delta, const git_diff_hunk *range, void *payload) {
godot::DiffHelper *diff_helper = (godot::DiffHelper *)payload;
DiffHelper *diff_helper = (DiffHelper *)payload;
godot::Dictionary hunk = diff_helper->git_api->create_diff_hunk(range->old_start, range->new_start, range->old_lines, range->new_lines);
godot::Dictionary hunk = diff_helper->git_plugin->create_diff_hunk(range->old_start, range->new_start, range->old_lines, range->new_lines);
diff_helper->diff_hunks->push_back(hunk);
return 1;
}
}

View File

@@ -1,18 +1,13 @@
#ifndef GIT_COMMON_H
#define GIT_COMMON_H
#pragma once
#include <cstdio>
#include "godot_cpp/variant/array.hpp"
#include "git2.h"
#include <Godot.hpp>
class GitPlugin;
#include <git2.h>
struct Credentials {
godot::String username;
godot::String password;
godot::String ssh_public_key_path;
godot::String ssh_private_key_path;
godot::String ssh_passphrase;
struct DiffHelper {
godot::Array *diff_hunks;
GitPlugin *git_plugin;
};
extern "C" int progress_cb(const char *str, int len, void *data);
@@ -23,5 +18,3 @@ extern "C" int credentials_cb(git_cred **out, const char *url, const char *usern
extern "C" int push_transfer_progress_cb(unsigned int current, unsigned int total, size_t bytes, void *payload);
extern "C" int push_update_reference_cb(const char *refname, const char *status, void *data);
extern "C" int diff_hunk_cb(const git_diff_delta *delta, const git_diff_hunk *range, void *payload);
#endif // !GIT_COMMON_H

View File

@@ -1,4 +1,10 @@
#include "git_api.h"
#include "git_plugin.h"
#include <cstring>
#include <git2/tree.h>
#include "godot_cpp/core/class_db.hpp"
#include "godot_cpp/classes/file.hpp"
#define GIT2_CALL(error, msg) \
if (check_errors(error, __FUNCTION__, __FILE__, __LINE__, msg)) { \
@@ -22,35 +28,25 @@
#define COMMA ,
namespace godot {
void GitAPI::_register_methods() {
register_method("_commit", &GitAPI::_commit);
register_method("_get_modified_files_data", &GitAPI::_get_modified_files_data);
register_method("_get_remotes", &GitAPI::_get_remotes);
register_method("_get_diff", &GitAPI::_get_diff);
register_method("_get_vcs_name", &GitAPI::_get_vcs_name);
register_method("_initialize", &GitAPI::_initialize);
register_method("_shut_down", &GitAPI::_shut_down);
register_method("_stage_file", &GitAPI::_stage_file);
register_method("_discard_file", &GitAPI::_discard_file);
register_method("_unstage_file", &GitAPI::_unstage_file);
register_method("_get_previous_commits", &GitAPI::_get_previous_commits);
register_method("_get_branch_list", &GitAPI::_get_branch_list);
register_method("_create_branch", &GitAPI::_create_branch);
register_method("_create_remote", &GitAPI::_create_remote);
register_method("_remove_branch", &GitAPI::_remove_branch);
register_method("_remove_remote", &GitAPI::_remove_remote);
register_method("_get_current_branch_name", &GitAPI::_get_current_branch_name);
register_method("_checkout_branch", &GitAPI::_checkout_branch);
register_method("_fetch", &GitAPI::_fetch);
register_method("_pull", &GitAPI::_pull);
register_method("_push", &GitAPI::_push);
register_method("_get_line_diff", &GitAPI::_get_line_diff);
register_method("_set_credentials", &GitAPI::_set_credentials);
void GitPlugin::_bind_methods() {
// Doesn't seem to require binding functions for now
}
bool GitAPI::check_errors(int error, String function, String file, int line, String message, const std::vector<git_error_code> &ignores) {
GitPlugin::GitPlugin() {
map_changes[GIT_STATUS_WT_NEW] = CHANGE_TYPE_NEW;
map_changes[GIT_STATUS_INDEX_NEW] = CHANGE_TYPE_NEW;
map_changes[GIT_STATUS_WT_MODIFIED] = CHANGE_TYPE_MODIFIED;
map_changes[GIT_STATUS_INDEX_MODIFIED] = CHANGE_TYPE_MODIFIED;
map_changes[GIT_STATUS_WT_RENAMED] = CHANGE_TYPE_RENAMED;
map_changes[GIT_STATUS_INDEX_RENAMED] = CHANGE_TYPE_RENAMED;
map_changes[GIT_STATUS_WT_DELETED] = CHANGE_TYPE_DELETED;
map_changes[GIT_STATUS_INDEX_DELETED] = CHANGE_TYPE_DELETED;
map_changes[GIT_STATUS_WT_TYPECHANGE] = CHANGE_TYPE_TYPECHANGE;
map_changes[GIT_STATUS_INDEX_TYPECHANGE] = CHANGE_TYPE_TYPECHANGE;
map_changes[GIT_STATUS_CONFLICTED] = CHANGE_TYPE_UNMERGED;
}
bool GitPlugin::check_errors(int error, godot::String function, godot::String file, int line, godot::String message, const std::vector<git_error_code> &ignores) {
const git_error *lg2err;
if (error == 0) {
@@ -63,18 +59,18 @@ bool GitAPI::check_errors(int error, String function, String file, int line, Str
}
}
message += ".";
message = message + ".";
if ((lg2err = git_error_last()) != nullptr && lg2err->message != nullptr) {
message += " Error " + String::num_int64(error) + ": ";
message += String(lg2err->message);
message = message + " Error " + godot::String::num_int64(error) + ": ";
message = message + godot::String(lg2err->message);
}
Godot::print_error("GitAPI: " + message, function, file, line);
std::cout << "GitPlugin: " << CString(message).data << " in " << CString(file).data << ":" << CString(function).data << "#L" << line << std::endl;
popup_error(message);
return true;
}
void GitAPI::_set_credentials(const String username, const String password, const String ssh_public_key_path, const String ssh_private_key_path, const String ssh_passphrase) {
void GitPlugin::_set_credentials(const godot::String &username, const godot::String &password, const godot::String &ssh_public_key_path, const godot::String &ssh_private_key_path, const godot::String &ssh_passphrase) {
creds.username = username;
creds.password = password;
creds.ssh_public_key_path = ssh_public_key_path;
@@ -82,7 +78,7 @@ void GitAPI::_set_credentials(const String username, const String password, cons
creds.ssh_passphrase = ssh_passphrase;
}
void GitAPI::_discard_file(const String file_path) {
void GitPlugin::_discard_file(const godot::String &file_path) {
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
CString c_path(file_path);
char *paths[] = { c_path.data };
@@ -92,7 +88,7 @@ void GitAPI::_discard_file(const String file_path) {
GIT2_CALL(git_checkout_index(repo.get(), nullptr, &opts), "Could not checkout index");
}
void GitAPI::_commit(const String msg) {
void GitPlugin::_commit(const godot::String &msg) {
git_index_ptr repo_index;
GIT2_CALL(git_repository_index(Capture(repo_index), repo.get()), "Could not get repository index");
@@ -152,7 +148,7 @@ void GitAPI::_commit(const String msg) {
}
}
void GitAPI::_stage_file(const String file_path) {
void GitPlugin::_stage_file(const godot::String &file_path) {
CString c_path(file_path);
char *paths[] = { c_path.data };
git_strarray array = { paths, 1 };
@@ -163,7 +159,7 @@ void GitAPI::_stage_file(const String file_path) {
GIT2_CALL(git_index_write(index.get()), "Could not write changes to disk");
}
void GitAPI::_unstage_file(const String file_path) {
void GitPlugin::_unstage_file(const godot::String &file_path) {
CString c_path(file_path);
char *paths[] = { c_path.data };
git_strarray array = { paths, 1 };
@@ -187,29 +183,20 @@ void GitAPI::_unstage_file(const String file_path) {
}
}
void GitAPI::create_gitignore_and_gitattributes() {
File *file = File::_new();
if (!file->file_exists("res://.gitignore")) {
file->open("res://.gitignore", File::ModeFlags::WRITE);
file->store_string(
"# Godot-specific ignores\n"
".import/\n"
"export.cfg\n"
"export_presets.cfg\n\n"
"# Imported translations (automatically generated from CSV files)\n"
"*.translation\n\n"
"# Mono-specific ignores\n"
".mono/\n"
"data_*/\n");
file->close();
void GitPlugin::create_gitignore_and_gitattributes() {
if (!godot::File::file_exists(repo_project_path + "/.gitignore")) {
godot::File file;
file.open(repo_project_path + "/.gitignore", godot::File::ModeFlags::WRITE);
file.store_string(
"# Godot 4+ specific ignores\n"
".godot/\n");
file.close();
}
if (!file->file_exists("res://.gitattributes")) {
file->open("res://.gitattributes", File::ModeFlags::WRITE);
file->store_string(
if (!godot::File::file_exists(repo_project_path + "/.gitattributes")) {
godot::File file;
file.open(repo_project_path + "/.gitattributes", godot::File::ModeFlags::WRITE);
file.store_string(
"# Set the default behavior, in case people don't have core.autocrlf set.\n"
"* text=auto\n\n"
@@ -227,14 +214,12 @@ void GitAPI::create_gitignore_and_gitattributes() {
"# Denote all files that are truly binary and should not be modified.\n"
"*.png binary\n"
"*.jpg binary\n");
file->close();
file.close();
}
file->free();
}
Array GitAPI::_get_modified_files_data() {
Array stats_files;
godot::Array GitPlugin::_get_modified_files_data() {
godot::Array stats_files;
git_status_options opts = GIT_STATUS_OPTIONS_INIT;
opts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
@@ -242,45 +227,32 @@ Array GitAPI::_get_modified_files_data() {
opts.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX | GIT_STATUS_OPT_SORT_CASE_SENSITIVELY | GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS;
git_status_list_ptr statuses;
GIT2_CALL_R(git_status_list_new(Capture(statuses), repo.get(), &opts), "Could not get status information from repository", Array());
GIT2_CALL_R(git_status_list_new(Capture(statuses), repo.get(), &opts), "Could not get status information from repository", godot::Array());
size_t count = git_status_list_entrycount(statuses.get());
for (size_t i = 0; i < count; ++i) {
const git_status_entry *entry = git_status_byindex(statuses.get(), i);
String path;
godot::String path;
if (entry->index_to_workdir) {
path = entry->index_to_workdir->new_file.path;
} else {
path = entry->head_to_index->new_file.path;
}
static Dictionary map_changes = Dictionary::make(
GIT_STATUS_WT_NEW, CHANGE_TYPE_NEW,
GIT_STATUS_INDEX_NEW, CHANGE_TYPE_NEW,
GIT_STATUS_WT_MODIFIED, CHANGE_TYPE_MODIFIED,
GIT_STATUS_INDEX_MODIFIED, CHANGE_TYPE_MODIFIED,
GIT_STATUS_WT_RENAMED, CHANGE_TYPE_RENAMED,
GIT_STATUS_INDEX_RENAMED, CHANGE_TYPE_RENAMED,
GIT_STATUS_WT_DELETED, CHANGE_TYPE_DELETED,
GIT_STATUS_INDEX_DELETED, CHANGE_TYPE_DELETED,
GIT_STATUS_WT_TYPECHANGE, CHANGE_TYPE_TYPECHANGE,
GIT_STATUS_INDEX_TYPECHANGE, CHANGE_TYPE_TYPECHANGE,
GIT_STATUS_CONFLICTED, CHANGE_TYPE_UNMERGED);
const static int git_status_wt = GIT_STATUS_WT_NEW | GIT_STATUS_WT_MODIFIED | GIT_STATUS_WT_DELETED | GIT_STATUS_WT_TYPECHANGE | GIT_STATUS_WT_RENAMED | GIT_STATUS_CONFLICTED;
const static int git_status_index = GIT_STATUS_INDEX_NEW | GIT_STATUS_INDEX_MODIFIED | GIT_STATUS_INDEX_DELETED | GIT_STATUS_INDEX_RENAMED | GIT_STATUS_INDEX_TYPECHANGE;
if (entry->status & git_status_wt) {
stats_files.push_back(create_status_file(path, map_changes[entry->status & git_status_wt], TREE_AREA_UNSTAGED));
stats_files.push_back(create_status_file(path, map_changes[git_status_t(entry->status & git_status_wt)], TREE_AREA_UNSTAGED));
}
if (entry->status & git_status_index) {
if (entry->status == GIT_STATUS_INDEX_RENAMED) {
String old_path = entry->head_to_index->old_file.path;
stats_files.push_back(create_status_file(old_path, map_changes[GIT_STATUS_INDEX_DELETED], TREE_AREA_STAGED));
stats_files.push_back(create_status_file(path, map_changes[GIT_STATUS_INDEX_NEW], TREE_AREA_STAGED));
godot::String old_path = entry->head_to_index->old_file.path;
stats_files.push_back(create_status_file(old_path, map_changes.at(GIT_STATUS_INDEX_DELETED), TREE_AREA_STAGED));
stats_files.push_back(create_status_file(path, map_changes.at(GIT_STATUS_INDEX_NEW), TREE_AREA_STAGED));
} else {
stats_files.push_back(create_status_file(path, map_changes[entry->status & git_status_index], TREE_AREA_STAGED));
stats_files.push_back(create_status_file(path, map_changes.at(git_status_t(entry->status & git_status_index)), TREE_AREA_STAGED));
}
}
}
@@ -288,31 +260,31 @@ Array GitAPI::_get_modified_files_data() {
return stats_files;
}
Array GitAPI::_get_branch_list() {
godot::Array GitPlugin::_get_branch_list() {
git_branch_iterator_ptr it;
GIT2_CALL_R(git_branch_iterator_new(Capture(it), repo.get(), GIT_BRANCH_LOCAL), "Could not create branch iterator", Array());
GIT2_CALL_R(git_branch_iterator_new(Capture(it), repo.get(), GIT_BRANCH_LOCAL), "Could not create branch iterator", godot::Array());
Array branch_names;
godot::Array branch_names;
git_reference_ptr ref;
git_branch_t type;
while (git_branch_next(Capture(ref), &type, it.get()) != GIT_ITEROVER) {
const char *name = nullptr;
GIT2_CALL_R(git_branch_name(&name, ref.get()), "Could not get branch name", Array());
GIT2_CALL_R(git_branch_name(&name, ref.get()), "Could not get branch name", godot::Array());
if (git_branch_is_head(ref.get())) {
// Always send the current branch as the first branch in list
branch_names.push_front(name);
} else {
branch_names.push_back(String(name));
branch_names.push_back(godot::String(name));
}
}
return branch_names;
}
void GitAPI::_create_branch(const String branch_name) {
void GitPlugin::_create_branch(const godot::String &branch_name) {
git_oid head_commit_id;
GIT2_CALL(git_reference_name_to_id(&head_commit_id, repo.get(), "HEAD"), "Could not get HEAD commit ID");
@@ -323,51 +295,51 @@ void GitAPI::_create_branch(const String branch_name) {
GIT2_CALL(git_branch_create(Capture(branch_ref), repo.get(), CString(branch_name).data, head_commit.get(), 0), "Could not create branch from HEAD");
}
void GitAPI::_create_remote(const String remote_name, const String remote_url) {
void GitPlugin::_create_remote(const godot::String &remote_name, const godot::String &remote_url) {
git_remote_ptr remote;
GIT2_CALL(git_remote_create(Capture(remote), repo.get(), CString(remote_name).data, CString(remote_url).data), "Could not create remote");
}
void GitAPI::_remove_branch(const String branch_name) {
void GitPlugin::_remove_branch(const godot::String &branch_name) {
git_reference_ptr branch;
GIT2_CALL(git_branch_lookup(Capture(branch), repo.get(), CString(branch_name).data, GIT_BRANCH_LOCAL), "Could not find branch " + branch_name);
GIT2_CALL(git_branch_delete(branch.get()), "Could not delete branch reference of " + branch_name);
}
void GitAPI::_remove_remote(const String remote_name) {
void GitPlugin::_remove_remote(const godot::String &remote_name) {
GIT2_CALL(git_remote_delete(repo.get(), CString(remote_name).data), "Could not delete remote " + remote_name);
}
Array GitAPI::_get_line_diff(String file_path, String text) {
godot::Array GitPlugin::_get_line_diff(const godot::String &file_path, const godot::String &text) {
git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
opts.context_lines = 0;
opts.flags = GIT_DIFF_DISABLE_PATHSPEC_MATCH | GIT_DIFF_INCLUDE_UNTRACKED;
git_index_ptr index;
GIT2_CALL_R(git_repository_index(Capture(index), repo.get()), "Failed to get repository index", Array());
GIT2_CALL_R(git_index_read(index.get(), 0), "Failed to read index", Array());
GIT2_CALL_R(git_repository_index(Capture(index), repo.get()), "Failed to get repository index", godot::Array());
GIT2_CALL_R(git_index_read(index.get(), 0), "Failed to read index", godot::Array());
const git_index_entry *entry = git_index_get_bypath(index.get(), CString(file_path).data, GIT_INDEX_STAGE_NORMAL);
if (!entry) {
return Array();
return godot::Array();
}
git_reference_ptr head;
GIT2_CALL_R(git_repository_head(Capture(head), repo.get()), "Failed to load repository head", Array());
GIT2_CALL_R(git_repository_head(Capture(head), repo.get()), "Failed to load repository head", godot::Array());
git_blob_ptr blob;
GIT2_CALL_R(git_blob_lookup(Capture(blob), repo.get(), &entry->id), "Failed to load head blob", Array());
GIT2_CALL_R(git_blob_lookup(Capture(blob), repo.get(), &entry->id), "Failed to load head blob", godot::Array());
Array diff_contents;
godot::Array diff_contents;
DiffHelper diff_helper = { &diff_contents, this };
GIT2_CALL_R(git_diff_blob_to_buffer(blob.get(), nullptr, CString(text).data, text.length(), nullptr, &opts, nullptr, nullptr, diff_hunk_cb, nullptr, &diff_helper), "Failed to make diff", Array());
GIT2_CALL_R(git_diff_blob_to_buffer(blob.get(), nullptr, CString(text).data, text.length(), nullptr, &opts, nullptr, nullptr, diff_hunk_cb, nullptr, &diff_helper), "Failed to make diff", godot::Array());
return diff_contents;
}
String GitAPI::_get_current_branch_name() {
godot::String GitPlugin::_get_current_branch_name() {
git_reference_ptr head;
GIT2_CALL_R_IGNORE(git_repository_head(Capture(head), repo.get()), "Could not find repository HEAD", "", { GIT_ENOTFOUND COMMA GIT_EUNBORNBRANCH });
@@ -385,11 +357,11 @@ String GitAPI::_get_current_branch_name() {
return name;
}
Array GitAPI::_get_remotes() {
godot::Array GitPlugin::_get_remotes() {
git_strarray remote_array;
GIT2_CALL_R(git_remote_list(&remote_array, repo.get()), "Could not get list of remotes", Array());
GIT2_CALL_R(git_remote_list(&remote_array, repo.get()), "Could not get list of remotes", godot::Array());
Array remotes;
godot::Array remotes;
for (int i = 0; i < remote_array.count; i++) {
remotes.push_back(remote_array.strings[i]);
}
@@ -397,25 +369,25 @@ Array GitAPI::_get_remotes() {
return remotes;
}
Array GitAPI::_get_previous_commits(const int64_t max_commits) {
godot::Array GitPlugin::_get_previous_commits(int64_t max_commits) {
git_revwalk_ptr walker;
GIT2_CALL_R(git_revwalk_new(Capture(walker), repo.get()), "Could not create new revwalk", Array());
GIT2_CALL_R(git_revwalk_sorting(walker.get(), GIT_SORT_TIME), "Could not sort revwalk by time", Array());
GIT2_CALL_R(git_revwalk_new(Capture(walker), repo.get()), "Could not create new revwalk", godot::Array());
GIT2_CALL_R(git_revwalk_sorting(walker.get(), GIT_SORT_TIME), "Could not sort revwalk by time", godot::Array());
GIT2_CALL_R_IGNORE(git_revwalk_push_head(walker.get()), "Could not push HEAD to revwalk", Array(), { GIT_ENOTFOUND COMMA GIT_ERROR });
GIT2_CALL_R_IGNORE(git_revwalk_push_head(walker.get()), "Could not push HEAD to revwalk", godot::Array(), { GIT_ENOTFOUND COMMA GIT_ERROR });
git_oid oid;
Array commits;
godot::Array commits;
char commit_id[GIT_OID_HEXSZ + 1];
for (int i = 0; !git_revwalk_next(&oid, walker.get()) && i <= max_commits; i++) {
git_commit_ptr commit;
GIT2_CALL_R(git_commit_lookup(Capture(commit), repo.get(), &oid), "Failed to lookup the commit", commits);
git_oid_tostr(commit_id, GIT_OID_HEXSZ + 1, git_commit_id(commit.get()));
String msg = git_commit_message(commit.get());
godot::String msg = git_commit_message(commit.get());
const git_signature *sig = git_commit_author(commit.get());
String author = String() + sig->name + " <" + sig->email + ">";
godot::String author = godot::String() + sig->name + " <" + sig->email + ">";
commits.push_back(create_commit(msg, author, commit_id, sig->when.time, sig->when.offset));
}
@@ -423,8 +395,8 @@ Array GitAPI::_get_previous_commits(const int64_t max_commits) {
return commits;
}
void GitAPI::_fetch(String remote) {
Godot::print("GitAPI: Performing fetch from " + remote);
void GitPlugin::_fetch(const godot::String &remote) {
std::cout << "GitPlugin: Performing fetch from " << CString(remote).data << std::endl;
git_remote_ptr remote_object;
GIT2_CALL(git_remote_lookup(Capture(remote_object), repo.get(), CString(remote).data), "Could not lookup remote \"" + remote + "\"");
@@ -444,11 +416,11 @@ void GitAPI::_fetch(String remote) {
opts.callbacks = remote_cbs;
GIT2_CALL(git_remote_fetch(remote_object.get(), nullptr, &opts, "fetch"), "Could not fetch data from remote");
Godot::print("GitAPI: Fetch ended");
std::cout << "GitPlugin: Fetch ended" << std::endl;
}
void GitAPI::_pull(String remote) {
Godot::print("GitAPI: Performing pull from " + remote);
void GitPlugin::_pull(const godot::String &remote) {
std::cout << "GitPlugin: Performing pull from " << CString(remote).data << std::endl;
git_remote_ptr remote_object;
GIT2_CALL(git_remote_lookup(Capture(remote_object), repo.get(), CString(remote).data), "Could not lookup remote \"" + remote + "\"");
@@ -467,7 +439,7 @@ void GitAPI::_pull(String remote) {
git_fetch_options fetch_opts = GIT_FETCH_OPTIONS_INIT;
fetch_opts.callbacks = remote_cbs;
String branch_name = _get_current_branch_name();
godot::String branch_name = _get_current_branch_name();
CString ref_spec_str("refs/heads/" + branch_name);
@@ -480,7 +452,7 @@ void GitAPI::_pull(String remote) {
GIT2_CALL(git_repository_fetchhead_foreach(repo.get(), fetchhead_foreach_cb, &pull_merge_oid), "Could not read \"FETCH_HEAD\" file");
if (git_oid_is_zero(&pull_merge_oid)) {
popup_error("GitAPI: Could not find remote branch HEAD for " + branch_name + ". Try pushing the branch first.");
popup_error("GitPlugin: Could not find remote branch HEAD for " + branch_name + ". Try pushing the branch first.");
return;
}
@@ -501,7 +473,7 @@ void GitAPI::_pull(String remote) {
GIT2_CALL(git_repository_head(Capture(target_ref), repo.get()), "Failed to get HEAD reference");
git_object_ptr target;
GIT2_CALL(git_object_lookup(Capture(target), repo.get(), &pull_merge_oid, GIT_OBJECT_COMMIT), "Failed to lookup OID " + String(git_oid_tostr_s(&pull_merge_oid)));
GIT2_CALL(git_object_lookup(Capture(target), repo.get(), &pull_merge_oid, GIT_OBJECT_COMMIT), "Failed to lookup OID " + godot::String(git_oid_tostr_s(&pull_merge_oid)));
ff_checkout_options.checkout_strategy = GIT_CHECKOUT_SAFE;
GIT2_CALL(git_checkout_tree(repo.get(), target.get(), &ff_checkout_options), "Failed to checkout HEAD reference");
@@ -509,7 +481,7 @@ void GitAPI::_pull(String remote) {
git_reference_ptr new_target_ref;
GIT2_CALL(git_reference_set_target(Capture(new_target_ref), target_ref.get(), &pull_merge_oid, nullptr), "Failed to move HEAD reference");
Godot::print("GitAPI: Fast Forwarded");
std::cout << "GitPlugin: Fast Forwarded" << std::endl;
GIT2_CALL(git_repository_state_cleanup(repo.get()), "Could not clean repository state");
} else if (merge_analysis & GIT_MERGE_ANALYSIS_NORMAL) {
@@ -525,27 +497,27 @@ void GitAPI::_pull(String remote) {
GIT2_CALL(git_repository_index(Capture(index), repo.get()), "Could not get repository index");
if (git_index_has_conflicts(index.get())) {
popup_error("GitAPI: Index has conflicts, Solve conflicts and make a merge commit.");
popup_error("GitPlugin: Index has conflicts, Solve conflicts and make a merge commit.");
} else {
popup_error("GitAPI: Change are staged, make a merge commit.");
popup_error("GitPlugin: Change are staged, make a merge commit.");
}
has_merge = true;
} else if (merge_analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE) {
Godot::print("GitAPI: Already up to date");
std::cout << "GitPlugin: Already up to date" << std::endl;
GIT2_CALL(git_repository_state_cleanup(repo.get()), "Could not clean repository state");
} else {
Godot::print("GitAPI: Can not merge");
std::cout << "GitPlugin: Can not merge" << std::endl;
}
Godot::print("GitAPI: Pull ended");
std::cout << "GitPlugin: Pull ended" << std::endl;
}
void GitAPI::_push(const String remote, const bool force) {
Godot::print("GitAPI: Performing push to " + remote);
void GitPlugin::_push(const godot::String &remote, bool force) {
std::cout << "GitPlugin: Performing push to " << CString(remote).data << std::endl;
git_remote_ptr remote_object;
GIT2_CALL(git_remote_lookup(Capture(remote_object), repo.get(), CString(remote).data), "Could not lookup remote \"" + remote + "\"");
@@ -561,9 +533,9 @@ void GitAPI::_push(const String remote, const bool force) {
GIT2_CALL(git_remote_connect(remote_object.get(), GIT_DIRECTION_PUSH, &remote_cbs, nullptr, nullptr), "Could not connect to remote \"" + remote + "\". Are your credentials correct? Try using a PAT token (in case you are using Github) as your password");
String branch_name = _get_current_branch_name();
godot::String branch_name = _get_current_branch_name();
CString pushspec(String() + (force ? "+" : "") + "refs/heads/" + branch_name);
CString pushspec(godot::String() + (force ? "+" : "") + "refs/heads/" + branch_name);
const git_strarray refspec = { &pushspec.data, 1 };
git_push_options push_options = GIT_PUSH_OPTIONS_INIT;
@@ -571,10 +543,10 @@ void GitAPI::_push(const String remote, const bool force) {
GIT2_CALL(git_remote_push(remote_object.get(), &refspec, &push_options), "Failed to push");
Godot::print("GitAPI: Push ended");
std::cout << "GitPlugin: Push ended" << std::endl;
}
bool GitAPI::_checkout_branch(String branch_name) {
bool GitPlugin::_checkout_branch(const godot::String &branch_name) {
git_reference_ptr branch;
GIT2_CALL_R(git_branch_lookup(Capture(branch), repo.get(), CString(branch_name).data, GIT_BRANCH_LOCAL), "Could not find branch", false);
const char *branch_ref_name = git_reference_name(branch.get());
@@ -590,9 +562,9 @@ bool GitAPI::_checkout_branch(String branch_name) {
return true;
}
Array GitAPI::_get_diff(const String identifier, const int64_t area) {
godot::Array GitPlugin::_get_diff(const godot::String &identifier, const int64_t area) {
git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
Array diff_contents;
godot::Array diff_contents;
opts.context_lines = 2;
opts.interhunk_lines = 0;
@@ -651,34 +623,36 @@ Array GitAPI::_get_diff(const String identifier, const int64_t area) {
return diff_contents;
}
Array GitAPI::_parse_diff(git_diff *diff) {
Array diff_contents;
godot::Array GitPlugin::_parse_diff(git_diff *diff) {
godot::Array diff_contents;
for (int i = 0; i < git_diff_num_deltas(diff); i++) {
const git_diff_delta *delta = git_diff_get_delta(diff, i);
git_patch_ptr patch;
GIT2_CALL_R(git_patch_from_diff(Capture(patch), diff, i), "Could not create patch from diff", Array());
GIT2_CALL_R(git_patch_from_diff(Capture(patch), diff, i), "Could not create patch from diff", godot::Array());
Dictionary diff_file = create_diff_file(delta->new_file.path, delta->old_file.path);
godot::Dictionary diff_file = create_diff_file(delta->new_file.path, delta->old_file.path);
Array diff_hunks;
godot::Array diff_hunks;
for (int j = 0; j < git_patch_num_hunks(patch.get()); j++) {
const git_diff_hunk *git_hunk;
size_t line_count;
GIT2_CALL_R(git_patch_get_hunk(&git_hunk, &line_count, patch.get(), j), "Could not get hunk from patch", Array());
GIT2_CALL_R(git_patch_get_hunk(&git_hunk, &line_count, patch.get(), j), "Could not get hunk from patch", godot::Array());
Dictionary diff_hunk = create_diff_hunk(git_hunk->old_start, git_hunk->new_start, git_hunk->old_lines, git_hunk->new_lines);
godot::Dictionary diff_hunk = create_diff_hunk(git_hunk->old_start, git_hunk->new_start, git_hunk->old_lines, git_hunk->new_lines);
Array diff_lines;
godot::Array diff_lines;
for (int k = 0; k < line_count; k++) {
const git_diff_line *git_diff_line;
GIT2_CALL_R(git_patch_get_line_in_hunk(&git_diff_line, patch.get(), j, k), "Could not get line from hunk in patch", Array());
GIT2_CALL_R(git_patch_get_line_in_hunk(&git_diff_line, patch.get(), j, k), "Could not get line from hunk in patch", godot::Array());
char *content = new char[git_diff_line->content_len + 1];
memcpy(content, git_diff_line->content, git_diff_line->content_len);
std::memcpy(content, git_diff_line->content, git_diff_line->content_len);
content[git_diff_line->content_len] = '\0';
diff_lines.push_back(create_diff_line(git_diff_line->new_lineno, git_diff_line->old_lineno, String(content), String(git_diff_line->origin)));
godot::String status = " "; // We reserve 1 null terminated space to fill the + or the - character at git_diff_line->origin
status[0] = git_diff_line->origin;
diff_lines.push_back(create_diff_line(git_diff_line->new_lineno, git_diff_line->old_lineno, godot::String(content), status));
delete[] content;
}
@@ -692,13 +666,17 @@ Array GitAPI::_parse_diff(git_diff *diff) {
return diff_contents;
}
String GitAPI::_get_vcs_name() {
godot::String GitPlugin::_get_vcs_name() {
return "Git";
}
bool GitAPI::_initialize(String project_path) {
bool GitPlugin::_initialize(const godot::String &project_path) {
using namespace godot;
ERR_FAIL_COND_V(project_path == "", false);
repo_project_path = project_path;
int init = git_libgit2_init();
if (init > 1) {
WARN_PRINT("Multiple libgit2 instances are running");
@@ -716,13 +694,8 @@ bool GitAPI::_initialize(String project_path) {
return true;
}
bool GitAPI::_shut_down() {
bool GitPlugin::_shut_down() {
repo.reset(); // Destroy repo object before libgit2 shuts down
GIT2_CALL_R(git_libgit2_shutdown(), "Could not shutdown Git Plugin", false);
return true;
}
void GitAPI::_init() {
}
} // namespace godot

View File

@@ -0,0 +1,65 @@
#pragma once
#include <unordered_map>
#include "git_callbacks.h"
#include "git_wrappers.h"
#include "godot_cpp/classes/editor_vcs_interface.hpp"
#include "git2.h"
struct Credentials {
godot::String username;
godot::String password;
godot::String ssh_public_key_path;
godot::String ssh_private_key_path;
godot::String ssh_passphrase;
};
class GitPlugin : public godot::EditorVCSInterface {
GDCLASS(GitPlugin, godot::EditorVCSInterface);
protected:
static void _bind_methods();
public:
Credentials creds;
bool has_merge = false;
git_repository_ptr repo;
git_oid pull_merge_oid = {};
godot::String repo_project_path;
std::unordered_map<git_status_t, ChangeType> map_changes;
GitPlugin();
// Endpoints
bool _initialize(const godot::String &project_path) override;
void _set_credentials(const godot::String &username, const godot::String &password, const godot::String &ssh_public_key_path, const godot::String &ssh_private_key_path, const godot::String &ssh_passphrase) override;
godot::Array _get_modified_files_data() override;
void _stage_file(const godot::String &file_path) override;
void _unstage_file(const godot::String &file_path) override;
void _discard_file(const godot::String &file_path) override;
void _commit(const godot::String &msg) override;
godot::Array _get_diff(const godot::String &identifier, int64_t area) override;
bool _shut_down() override;
godot::String _get_vcs_name() override;
godot::Array _get_previous_commits(int64_t max_commits) override;
godot::Array _get_branch_list() override;
godot::Array _get_remotes() override;
void _create_branch(const godot::String &branch_name) override;
void _remove_branch(const godot::String &branch_name) override;
void _create_remote(const godot::String &remote_name, const godot::String &remote_url) override;
void _remove_remote(const godot::String &remote_name) override;
godot::String _get_current_branch_name() override;
bool _checkout_branch(const godot::String &branch_name) override;
void _pull(const godot::String &remote) override;
void _push(const godot::String &remote, bool force) override;
void _fetch(const godot::String &remote) override;
godot::Array _get_line_diff(const godot::String &file_path, const godot::String &text) override;
// Helpers
godot::Array _parse_diff(git_diff *p_diff);
bool check_errors(int error, godot::String function, godot::String file, int line, godot::String message, const std::vector<git_error_code> &ignores = {});
void create_gitignore_and_gitattributes();
bool create_initial_commit();
};

View File

@@ -0,0 +1,18 @@
#include "git_wrappers.h"
#include <cstring>
CString::CString(const godot::String &string) {
godot::CharString godot_char_str = string.utf8();
data = new char[godot_char_str.length() + 1];
std::memcpy(data, (void *)godot_char_str.get_data(), godot_char_str.length());
data[godot_char_str.length()] = '\0';
}
CString::~CString() {
if (data) {
delete[] data;
data = nullptr;
}
}

View File

@@ -0,0 +1,74 @@
#pragma once
#include <memory>
#include "godot_cpp/variant/string.hpp"
#include "git2.h"
class GitPlugin;
struct CString {
char *data = nullptr;
CString(const godot::String &string);
~CString();
CString() = delete;
CString(CString &&) = delete;
CString &operator=(const CString &) = delete;
CString &operator=(CString &&) = delete;
};
template <class T>
class Capture {
T &smart_ptr = nullptr;
using Raw = decltype(smart_ptr.get());
Raw raw = nullptr;
public:
Capture() = delete;
Capture(T &ptr) :
smart_ptr(ptr) {}
Capture(Capture &&) = delete;
Capture &operator=(const Capture &) = delete;
Capture &operator=(Capture &&) = delete;
operator Raw *() {
return &raw;
}
~Capture() {
if (raw) {
smart_ptr.reset(raw);
}
}
};
template <auto DeleteFn>
struct FunctionDeleter {
template <class T>
void operator()(T *ptr) {
DeleteFn(ptr);
}
};
template <class T, auto DeleteFn>
using unique_ptr_deleter = std::unique_ptr<T, FunctionDeleter<DeleteFn>>;
using git_annotated_commit_ptr = unique_ptr_deleter<git_annotated_commit, git_annotated_commit_free>;
using git_blob_ptr = unique_ptr_deleter<git_blob, git_blob_free>;
using git_branch_iterator_ptr = unique_ptr_deleter<git_branch_iterator, git_branch_iterator_free>;
using git_commit_ptr = unique_ptr_deleter<git_commit, git_commit_free>;
using git_diff_ptr = unique_ptr_deleter<git_diff, git_diff_free>;
using git_index_ptr = unique_ptr_deleter<git_index, git_index_free>;
using git_object_ptr = unique_ptr_deleter<git_object, git_object_free>;
using git_patch_ptr = unique_ptr_deleter<git_patch, git_patch_free>;
using git_reference_ptr = unique_ptr_deleter<git_reference, git_reference_free>;
using git_remote_ptr = unique_ptr_deleter<git_remote, git_remote_free>;
using git_repository_ptr = unique_ptr_deleter<git_repository, git_repository_free>;
using git_revwalk_ptr = unique_ptr_deleter<git_revwalk, git_revwalk_free>;
using git_signature_ptr = unique_ptr_deleter<git_signature, git_signature_free>;
using git_status_list_ptr = unique_ptr_deleter<git_status_list, git_status_list_free>;
using git_tree_ptr = unique_ptr_deleter<git_tree, git_tree_free>;
using git_tree_entry_ptr = unique_ptr_deleter<git_tree_entry, git_tree_entry_free>;

4
release.sh Executable file → Normal file
View File

@@ -35,9 +35,9 @@ addonsPath=$releasePath/addons
pluginPath=$addonsPath/godot-git-plugin
mkdir $pluginPath/linux
mkdir $pluginPath/osx
mkdir $pluginPath/macos
cp -r linux/addons/godot-git-plugin/linux/ $pluginPath/
cp -r mac/addons/godot-git-plugin/osx/ $pluginPath/
cp -r mac/addons/godot-git-plugin/macos/ $pluginPath/
sed -i "s/version=\"[^\"]*\"/version=\"v${version}\"/g" $pluginPath/plugin.cfg
cp LICENSE $pluginPath/LICENSE

2
thirdparty/SCsub vendored
View File

@@ -1,4 +1,6 @@
#!/usr/bin/env python
Import("env")
SConscript("ssh2/SCsub")
SConscript("git2/SCsub")

View File

@@ -85,7 +85,7 @@ if env_git["platform"] == "windows":
]
)
if env_git["platform"] in ["linux", "osx"]:
if env_git["platform"] in ["linux", "macos"]:
env_git.Append(CCFLAGS="-fPIC")
libgit2_sources += Glob("libgit2/src/unix/" + "*.c")
libgit2_sources += [
@@ -126,7 +126,7 @@ if env_git["platform"] in ["linux", "osx"]:
]
)
if env_git["platform"] == "osx":
if env_git["platform"] == "macos":
env_git.Prepend(CPPPATH=[env_git["macos_openssl"] + "include/"])
static_ssl = File(env_git["macos_openssl_static_ssl"])
static_crypto = File(env_git["macos_openssl_static_crypto"])

View File

@@ -57,7 +57,7 @@ if env_ssh2["platform"] == "windows":
)
env_ssh2.Append(LIBS=["crypt32", "user32"])
if env_ssh2["platform"] in ["linux", "osx"]:
if env_ssh2["platform"] in ["linux", "macos"]:
env_ssh2.Append(CCFLAGS="-fPIC")
env_ssh2.Append(
CPPPATH=[
@@ -104,7 +104,7 @@ if env_ssh2["platform"] in ["linux", "osx"]:
]
)
if env_ssh2["platform"] == "osx":
if env_ssh2["platform"] == "macos":
env_ssh2.Append(CPPPATH=[env_ssh2["macos_openssl"] + "include/"])
static_ssl = File(env_ssh2["macos_openssl_static_ssl"])
static_crypto = File(env_ssh2["macos_openssl_static_crypto"])