Format c++ files using clang-format

Add git pre-commit hooks to help with automatic formatting.
This commit is contained in:
Leroy Hopson 2021-06-06 19:58:50 +07:00 committed by Leroy Hopson
parent 99989d19e4
commit 6e455738b8
10 changed files with 981 additions and 760 deletions

View file

@ -3,18 +3,16 @@
#include "pseudoterminal.h"
#endif
extern "C" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *o)
{
extern "C" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *o) {
godot::Godot::gdnative_init(o);
}
extern "C" void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *o)
{
extern "C" void GDN_EXPORT
godot_gdnative_terminate(godot_gdnative_terminate_options *o) {
godot::Godot::gdnative_terminate(o);
}
extern "C" void GDN_EXPORT godot_nativescript_init(void *handle)
{
extern "C" void GDN_EXPORT godot_nativescript_init(void *handle) {
godot::Godot::nativescript_init(handle);
godot::register_tool_class<godot::Terminal>();

View file

@ -9,14 +9,13 @@
#include <pty.h>
#endif
#if defined(PLATFORM_OSX)
#include <util.h>
#include <sys/ioctl.h>
#include <util.h>
#endif
using namespace godot;
void Pseudoterminal::_register_methods()
{
void Pseudoterminal::_register_methods() {
register_method("_init", &Pseudoterminal::_init);
register_method("_ready", &Pseudoterminal::_ready);
@ -24,27 +23,22 @@ void Pseudoterminal::_register_methods()
register_method("write", &Pseudoterminal::write);
register_method("resize", &Pseudoterminal::resize);
register_signal<Pseudoterminal>((char *)"data_sent", "data", GODOT_VARIANT_TYPE_POOL_BYTE_ARRAY);
register_signal<Pseudoterminal>((char *)"exited", "status", GODOT_VARIANT_TYPE_INT);
register_signal<Pseudoterminal>((char *)"data_sent", "data",
GODOT_VARIANT_TYPE_POOL_BYTE_ARRAY);
register_signal<Pseudoterminal>((char *)"exited", "status",
GODOT_VARIANT_TYPE_INT);
}
Pseudoterminal::Pseudoterminal()
{
}
Pseudoterminal::Pseudoterminal() {}
Pseudoterminal::~Pseudoterminal()
{
pty_thread.join();
}
Pseudoterminal::~Pseudoterminal() { pty_thread.join(); }
void Pseudoterminal::_init()
{
void Pseudoterminal::_init() {
bytes_to_write = 0;
pty_thread = std::thread(&Pseudoterminal::process_pty, this);
}
void Pseudoterminal::process_pty()
{
void Pseudoterminal::process_pty() {
int fd;
char *name;
int status;
@ -61,14 +55,12 @@ void Pseudoterminal::process_pty()
pid_t pty_pid = forkpty(&fd, NULL, NULL, NULL);
if (pty_pid == -1)
{
ERR_PRINT(String("Error forking pty: {0}").format(Array::make(strerror(errno))));
if (pty_pid == -1) {
ERR_PRINT(
String("Error forking pty: {0}").format(Array::make(strerror(errno))));
should_process_pty = false;
return;
}
else if (pty_pid == 0)
{
} else if (pty_pid == 0) {
/* Child */
char termenv[11] = {"TERM=xterm"};
@ -78,20 +70,16 @@ void Pseudoterminal::process_pty()
putenv(colortermenv);
char *shell = getenv("SHELL");
char *argv[] = { basename(shell), NULL };
char *argv[] = {basename(shell), NULL};
execvp(shell, argv);
}
else
{
} else {
Vector2 zero = Vector2(0, 0);
/* Parent */
while (1)
{
while (1) {
{
std::lock_guard<std::mutex> guard(size_mutex);
if (size != zero)
{
if (size != zero) {
struct winsize ws;
memset(&ws, 0, sizeof(ws));
ws.ws_col = size.x;
@ -101,8 +89,7 @@ void Pseudoterminal::process_pty()
}
}
if (waitpid(pty_pid, &status, WNOHANG))
{
if (waitpid(pty_pid, &status, WNOHANG)) {
emit_signal("exited", status);
return;
}
@ -121,21 +108,17 @@ void Pseudoterminal::process_pty()
ready = select(fd + 1, &read_fds, &write_fds, NULL, &timeout);
if (ready > 0)
{
if (FD_ISSET(fd, &write_fds))
{
if (ready > 0) {
if (FD_ISSET(fd, &write_fds)) {
std::lock_guard<std::mutex> guard(write_buffer_mutex);
if (bytes_to_write > 0)
{
if (bytes_to_write > 0) {
::write(fd, write_buffer, bytes_to_write);
bytes_to_write = 0;
}
}
if (FD_ISSET(fd, &read_fds))
{
if (FD_ISSET(fd, &read_fds)) {
std::lock_guard<std::mutex> guard(read_buffer_mutex);
int ret;
@ -158,19 +141,15 @@ void Pseudoterminal::process_pty()
}
}
void Pseudoterminal::_ready()
{
}
void Pseudoterminal::_ready() {}
void Pseudoterminal::write(PoolByteArray data)
{
void Pseudoterminal::write(PoolByteArray data) {
std::lock_guard<std::mutex> guard(write_buffer_mutex);
bytes_to_write = data.size();
memcpy(write_buffer, data.read().ptr(), bytes_to_write);
}
void Pseudoterminal::resize(Vector2 new_size)
{
void Pseudoterminal::resize(Vector2 new_size) {
std::lock_guard<std::mutex> guard(size_mutex);
size = new_size;
}

View file

@ -3,21 +3,19 @@
#include <Godot.hpp>
#include <Node.hpp>
#include <thread>
#include <mutex>
#include <thread>
namespace godot
{
namespace godot {
class Pseudoterminal : public Node
{
class Pseudoterminal : public Node {
GODOT_CLASS(Pseudoterminal, Node)
public:
public:
static const int MAX_READ_BUFFER_LENGTH = 1024;
static const int MAX_WRITE_BUFFER_LENGTH = 1024;
private:
private:
std::thread pty_thread;
bool should_process_pty;
@ -34,7 +32,7 @@ namespace godot
void process_pty();
public:
public:
static void _register_methods();
Pseudoterminal();
@ -45,7 +43,7 @@ namespace godot
void write(PoolByteArray data);
void resize(Vector2 size);
};
};
} // namespace godot
#endif // PSEUDOTERMINAL_H

View file

@ -1,10 +1,10 @@
#include "terminal.h"
#include <algorithm>
#include <GlobalConstants.hpp>
#include <InputEventKey.hpp>
#include <OS.hpp>
#include <ResourceLoader.hpp>
#include <Theme.hpp>
#include <algorithm>
#include <xkbcommon/xkbcommon-keysyms.h>
using namespace godot;
@ -13,7 +13,8 @@ const struct Terminal::cell Terminal::empty_cell = {{0, 0, 0, 0, 0}, {}};
const std::map<std::pair<int64_t, int64_t>, uint32_t> Terminal::keymap = {
// Godot does not have seperate scancodes for keypad keys when NumLock is off.
// Godot does not have seperate scancodes for keypad keys when NumLock is
// off.
// We can check the unicode value to determine whether it is off and set the
// appropriate scancode.
// Based on the patch which adds support for this to TextEdit/LineEdit:
@ -175,18 +176,15 @@ const std::map<std::pair<int64_t, int64_t>, uint32_t> Terminal::keymap = {
//{{0, GlobalConstants::KEY_F20}, XKB_KEY_F20},
};
static struct
{
static struct {
Color col;
bool is_set;
} colours[16];
static void term_output(const char *s, size_t len, void *user)
{
}
static void term_output(const char *s, size_t len, void *user) {}
static void write_cb(struct tsm_vte *vte, const char *u8, size_t len, void *data)
{
static void write_cb(struct tsm_vte *vte, const char *u8, size_t len,
void *data) {
Terminal *term = static_cast<Terminal *>(data);
@ -195,11 +193,10 @@ static void write_cb(struct tsm_vte *vte, const char *u8, size_t len, void *data
for (int i = 0; i < len; i++)
bytes.append(u8[i]);
if (len > 0)
{
if (term->input_event_key.is_valid())
{
// The callback was fired from a key press event so emit the "key_pressed" signal.
if (len > 0) {
if (term->input_event_key.is_valid()) {
// The callback was fired from a key press event so emit the "key_pressed"
// signal.
term->emit_signal("key_pressed", String(u8), term->input_event_key);
term->input_event_key.unref();
}
@ -208,17 +205,10 @@ static void write_cb(struct tsm_vte *vte, const char *u8, size_t len, void *data
}
}
static int text_draw_cb(struct tsm_screen *con,
uint64_t id,
const uint32_t *ch,
size_t len,
unsigned int width,
unsigned int posx,
unsigned int posy,
const struct tsm_screen_attr *attr,
tsm_age_t age,
void *data)
{
static int text_draw_cb(struct tsm_screen *con, uint64_t id, const uint32_t *ch,
size_t len, unsigned int width, unsigned int posx,
unsigned int posy, const struct tsm_screen_attr *attr,
tsm_age_t age, void *data) {
Terminal *terminal = static_cast<Terminal *>(data);
@ -228,13 +218,10 @@ static int text_draw_cb(struct tsm_screen *con,
size_t ulen;
char buf[5] = {0};
if (len > 0)
{
if (len > 0) {
char *utf8 = tsm_ucs4_to_utf8_alloc(ch, len, &ulen);
memcpy(terminal->cells[posy][posx].ch, utf8, ulen);
}
else
{
} else {
terminal->cells[posy][posx] = {};
}
@ -246,8 +233,7 @@ static int text_draw_cb(struct tsm_screen *con,
return 0;
}
void Terminal::_register_methods()
{
void Terminal::_register_methods() {
register_method("_init", &Terminal::_init);
register_method("_ready", &Terminal::_ready);
register_method("_gui_input", &Terminal::_gui_input);
@ -260,47 +246,41 @@ void Terminal::_register_methods()
register_property<Terminal, int>("rows", &Terminal::rows, 24);
register_property<Terminal, int>("cols", &Terminal::cols, 80);
register_signal<Terminal>("data_sent", "data", GODOT_VARIANT_TYPE_POOL_BYTE_ARRAY);
register_signal<Terminal>("key_pressed", "data", GODOT_VARIANT_TYPE_STRING, "event", GODOT_VARIANT_TYPE_OBJECT);
register_signal<Terminal>("size_changed", "new_size", GODOT_VARIANT_TYPE_VECTOR2);
register_signal<Terminal>("data_sent", "data",
GODOT_VARIANT_TYPE_POOL_BYTE_ARRAY);
register_signal<Terminal>("key_pressed", "data", GODOT_VARIANT_TYPE_STRING,
"event", GODOT_VARIANT_TYPE_OBJECT);
register_signal<Terminal>("size_changed", "new_size",
GODOT_VARIANT_TYPE_VECTOR2);
}
Terminal::Terminal()
{
}
Terminal::Terminal() {}
Terminal::~Terminal()
{
}
Terminal::~Terminal() {}
void Terminal::_init()
{
void Terminal::_init() {
sleep = true;
if (tsm_screen_new(&screen, NULL, NULL))
{
if (tsm_screen_new(&screen, NULL, NULL)) {
ERR_PRINT("Error creating new tsm screen");
}
tsm_screen_set_max_sb(screen, 1000); // TODO: Use config var for scrollback size.
tsm_screen_set_max_sb(screen,
1000); // TODO: Use config var for scrollback size.
if (tsm_vte_new(&vte, screen, write_cb, this, NULL, NULL))
{
if (tsm_vte_new(&vte, screen, write_cb, this, NULL, NULL)) {
ERR_PRINT("Error creating new tsm vte");
}
update_theme();
}
void Terminal::_ready()
{
void Terminal::_ready() {
update_size();
connect("resized", this, "update_size");
}
void Terminal::_notification(int what)
{
switch (what)
{
void Terminal::_notification(int what) {
switch (what) {
case NOTIFICATION_RESIZED:
update_size();
break;
@ -310,14 +290,11 @@ void Terminal::_notification(int what)
}
}
void Terminal::_gui_input(Variant event)
{
void Terminal::_gui_input(Variant event) {
Ref<InputEventKey> k = event;
if (k.is_valid())
{
if (!k->is_pressed())
{
if (k.is_valid()) {
if (!k->is_pressed()) {
return;
}
@ -337,12 +314,12 @@ void Terminal::_gui_input(Variant event)
uint32_t keysym = (iter != keymap.end() ? iter->second : XKB_KEY_NoSymbol);
input_event_key = k;
tsm_vte_handle_keyboard(vte, keysym, ascii, mods, unicode ? unicode : TSM_VTE_INVALID);
tsm_vte_handle_keyboard(vte, keysym, ascii, mods,
unicode ? unicode : TSM_VTE_INVALID);
}
}
void Terminal::_draw()
{
void Terminal::_draw() {
if (sleep)
return;
@ -351,10 +328,8 @@ void Terminal::_draw()
draw_rect(Rect2(Vector2(0, 0), get_rect().size), background_color);
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
/* Draw cell background and foreground */
std::pair<Color, Color> color_pair = get_cell_colors(row, col);
draw_background(row, col, color_pair.first);
@ -363,13 +338,14 @@ void Terminal::_draw()
}
}
void Terminal::update_theme()
{
void Terminal::update_theme() {
/* Generate color palette based on theme */
// Converts a color from the Control's theme to one that can
// be used in a tsm color palette.
auto set_pallete_color = [this](tsm_vte_color color, String theme_color, int default_r, int default_g, int default_b) -> void {
auto set_pallete_color = [this](tsm_vte_color color, String theme_color,
int default_r, int default_g,
int default_b) -> void {
Color c;
if (has_color(theme_color, "Terminal")) {
@ -408,21 +384,18 @@ void Terminal::update_theme()
set_pallete_color(TSM_COLOR_BACKGROUND, "Background", 255, 255, 255);
set_pallete_color(TSM_COLOR_FOREGROUND, "Foreground", 0, 0, 0);
if (tsm_vte_set_custom_palette(vte, color_palette))
{
if (tsm_vte_set_custom_palette(vte, color_palette)) {
ERR_PRINT("Error setting custom palette");
}
if (tsm_vte_set_palette(vte, "custom"))
{
if (tsm_vte_set_palette(vte, "custom")) {
ERR_PRINT("Error setting palette");
}
/* Load fonts into the fontmap from theme */
auto set_font = [this](String font_style, String default_font_path) -> void {
Ref<Font> fontref;
ResourceLoader* rl = ResourceLoader::get_singleton();
ResourceLoader *rl = ResourceLoader::get_singleton();
if (has_font(font_style, "Terminal")) {
fontref = get_font(font_style, "Terminal");
@ -433,14 +406,19 @@ void Terminal::update_theme()
fontmap.insert(std::pair<String, Ref<Font>>(font_style, fontref));
};
set_font("Bold Italic", "res://addons/godot_xterm/themes/fonts/cousine/cousine_bold_italic.tres");
set_font("Bold", "res://addons/godot_xterm/themes/fonts/cousine/cousine_bold.tres");
set_font("Italic", "res://addons/godot_xterm/themes/fonts/cousine/cousine_italic.tres");
set_font("Regular", "res://addons/godot_xterm/themes/fonts/cousine/cousine_regular.tres");
set_font(
"Bold Italic",
"res://addons/godot_xterm/themes/fonts/cousine/cousine_bold_italic.tres");
set_font("Bold",
"res://addons/godot_xterm/themes/fonts/cousine/cousine_bold.tres");
set_font("Italic",
"res://addons/godot_xterm/themes/fonts/cousine/cousine_italic.tres");
set_font(
"Regular",
"res://addons/godot_xterm/themes/fonts/cousine/cousine_regular.tres");
}
void Terminal::draw_background(int row, int col, Color bgcolor)
{
void Terminal::draw_background(int row, int col, Color bgcolor) {
/* Draw the background */
Vector2 background_pos = Vector2(col * cell_size.x, row * cell_size.y);
@ -448,8 +426,7 @@ void Terminal::draw_background(int row, int col, Color bgcolor)
draw_rect(background_rect, bgcolor);
}
void Terminal::draw_foreground(int row, int col, Color fgcolor)
{
void Terminal::draw_foreground(int row, int col, Color fgcolor) {
struct cell cell = cells[row][col];
@ -460,20 +437,13 @@ void Terminal::draw_foreground(int row, int col, Color fgcolor)
Ref<Font> fontref = get_font("");
if (cell.attr.bold && cell.attr.italic)
{
if (cell.attr.bold && cell.attr.italic) {
fontref = fontmap["Bold Italic"];
}
else if (cell.attr.bold)
{
} else if (cell.attr.bold) {
fontref = fontmap["Bold"];
}
else if (cell.attr.italic)
{
} else if (cell.attr.italic) {
fontref = fontmap["Italic"];
}
else
{
} else {
fontref = fontmap["Regular"];
}
@ -483,54 +453,48 @@ void Terminal::draw_foreground(int row, int col, Color fgcolor)
; // TODO: Handle blink
int font_height = fontref.ptr()->get_height();
Vector2 foreground_pos = Vector2(col * cell_size.x, row * cell_size.y + font_height / 1.25);
Vector2 foreground_pos =
Vector2(col * cell_size.x, row * cell_size.y + font_height / 1.25);
draw_string(fontref, foreground_pos, cell.ch, fgcolor);
if (cell.attr.underline)
draw_string(fontref, foreground_pos, "_", fgcolor);
}
std::pair<Color, Color> Terminal::get_cell_colors(int row, int col)
{
std::pair<Color, Color> Terminal::get_cell_colors(int row, int col) {
struct cell cell = cells[row][col];
Color fgcol, bgcol;
float fr = 0, fg = 0, fb = 0, br = 1, bg = 1, bb = 1;
/* Get foreground color */
if (cell.attr.fccode && palette.count(cell.attr.fccode))
{
if (cell.attr.fccode && palette.count(cell.attr.fccode)) {
fgcol = palette[cell.attr.fccode];
}
else
{
} else {
fr = (float)cell.attr.fr / 255.0;
fg = (float)cell.attr.fg / 255.0;
fb = (float)cell.attr.fb / 255.0;
fgcol = Color(fr, fg, fb);
if (cell.attr.fccode != -1)
{
palette.insert(std::pair<int, Color>(cell.attr.fccode, Color(fr, fg, fb)));
if (cell.attr.fccode != -1) {
palette.insert(
std::pair<int, Color>(cell.attr.fccode, Color(fr, fg, fb)));
}
}
/* Get background color */
if (cell.attr.bccode && palette.count(cell.attr.bccode))
{
if (cell.attr.bccode && palette.count(cell.attr.bccode)) {
bgcol = palette[cell.attr.bccode];
}
else
{
} else {
br = (float)cell.attr.br / 255.0;
bg = (float)cell.attr.bg / 255.0;
bb = (float)cell.attr.bb / 255.0;
bgcol = Color(br, bg, bb);
if (cell.attr.bccode != -1)
{
palette.insert(std::pair<int, Color>(cell.attr.bccode, Color(br, bg, bb)));
if (cell.attr.bccode != -1) {
palette.insert(
std::pair<int, Color>(cell.attr.bccode, Color(br, bg, bb)));
}
}
@ -540,12 +504,16 @@ std::pair<Color, Color> Terminal::get_cell_colors(int row, int col)
return std::make_pair(bgcol, fgcol);
}
// Recalculates the cell_size and number of cols/rows based on font size and the Control's rect_size
void Terminal::update_size()
{
// Recalculates the cell_size and number of cols/rows based on font size and the
// Control's rect_size
void Terminal::update_size() {
sleep = true;
Ref<Font> fontref = fontmap.count("Regular") ? fontmap["Regular"] : has_font("Regular", "Terminal") ? get_font("Regular", "Terminal") : get_font("");
Ref<Font> fontref = fontmap.count("Regular")
? fontmap["Regular"]
: has_font("Regular", "Terminal")
? get_font("Regular", "Terminal")
: get_font("");
cell_size = fontref->get_string_size("W");
rows = std::max(2, (int)floor(get_rect().size.y / cell_size.y));
@ -555,18 +523,13 @@ void Terminal::update_size()
Cells new_cells = {};
for (int x = 0; x < rows; x++)
{
for (int x = 0; x < rows; x++) {
Row row(cols);
for (int y = 0; y < cols; y++)
{
if (x < cells.size() && y < cells[x].size())
{
for (int y = 0; y < cols; y++) {
if (x < cells.size() && y < cells[x].size()) {
row[y] = cells[x][y];
}
else
{
} else {
row[y] = empty_cell;
}
}
@ -583,23 +546,19 @@ void Terminal::update_size()
update();
}
void Terminal::write(Variant data)
{
void Terminal::write(Variant data) {
const char *u8;
size_t len;
switch (data.get_type())
{
case Variant::Type::POOL_BYTE_ARRAY:
{
switch (data.get_type()) {
case Variant::Type::POOL_BYTE_ARRAY: {
PoolByteArray bytes = data;
u8 = (char *)bytes.read().ptr();
len = bytes.size();
break;
}
case Variant::Type::STRING:
{
case Variant::Type::STRING: {
String string = data;
u8 = string.alloc_c_string();
len = strlen(u8);

View file

@ -1,29 +1,26 @@
#ifndef TERMINAL_H
#define TERMINAL_H
#include <libtsm.h>
#include <Control.hpp>
#include <Font.hpp>
#include <Godot.hpp>
#include <libtsm.h>
#include <map>
#include <vector>
namespace godot
{
namespace godot {
class Terminal : public Control
{
class Terminal : public Control {
GODOT_CLASS(Terminal, Control)
public:
struct cell
{
public:
struct cell {
char ch[5];
struct tsm_screen_attr attr;
};
static const struct cell empty_cell;
public:
public:
typedef std::vector<std::vector<struct cell>> Cells;
typedef std::vector<struct cell> Row;
@ -31,11 +28,11 @@ namespace godot
Ref<InputEventKey> input_event_key;
protected:
protected:
tsm_screen *screen;
tsm_vte *vte;
private:
private:
static const uint8_t default_color_palette[TSM_COLOR_NUM][3];
static const std::map<std::pair<int64_t, int64_t>, uint32_t> keymap;
@ -50,7 +47,7 @@ namespace godot
void draw_background(int row, int col, Color bgcol);
void draw_foreground(int row, int col, Color fgcol);
public:
public:
static void _register_methods();
Terminal();
@ -72,7 +69,7 @@ namespace godot
uint8_t color_palette[TSM_COLOR_NUM][3];
tsm_age_t framebuffer_age;
};
};
} // namespace godot
#endif // TERMINAL_H

21
misc/hooks/README.md Normal file
View file

@ -0,0 +1,21 @@
# Git hooks for GodotXterm
This folder contains git hooks meant to be installed locally by GodotXterm
contributors to make sure they comply with our requirements.
## List of hooks
- Pre-commit hook for gdformat: Applies formatting to staged gdscript files
using the [GDScript Toolkit](https://github.com/Scony/godot-gdscript-toolkit) by Pawel Lampe et al.
- Pre-commit hook for clang-format: Applies clang-format to the staged files
before accepting a commit; blocks the commit and generates a patch if the
style is not respected.
Should work on Linux and macOS. You may need to edit the file if your
clang-format binary is not in the $PATH, or if you want to enable colored
output with pygmentize.
## Installation
Symlink (or copy) all the files from this folder (except this README) into your .git/hooks folder, and make sure
the hooks and helper scripts are executable.

View file

@ -0,0 +1,48 @@
#!/bin/sh
# Provide the canonicalize filename (physical filename with out any symlinks)
# like the GNU version readlink with the -f option regardless of the version of
# readlink (GNU or BSD).
# This file is part of a set of unofficial pre-commit hooks available
# at github.
# Link: https://github.com/githubbrowser/Pre-commit-hooks
# Contact: David Martin, david.martin.mailbox@googlemail.com
###########################################################
# There should be no need to change anything below this line.
# Canonicalize by recursively following every symlink in every component of the
# specified filename. This should reproduce the results of the GNU version of
# readlink with the -f option.
#
# Reference: http://stackoverflow.com/questions/1055671/how-can-i-get-the-behavior-of-gnus-readlink-f-on-a-mac
canonicalize_filename () {
local target_file="$1"
local physical_directory=""
local result=""
# Need to restore the working directory after work.
local working_dir="`pwd`"
cd -- "$(dirname -- "$target_file")"
target_file="$(basename -- "$target_file")"
# Iterate down a (possible) chain of symlinks
while [ -L "$target_file" ]
do
target_file="$(readlink -- "$target_file")"
cd -- "$(dirname -- "$target_file")"
target_file="$(basename -- "$target_file")"
done
# Compute the canonicalized name by finding the physical path
# for the directory we're in and appending the target file.
physical_directory="`pwd -P`"
result="$physical_directory/$target_file"
# restore the working directory after work.
cd -- "$working_dir"
echo "$result"
}

50
misc/hooks/pre-commit Executable file
View file

@ -0,0 +1,50 @@
#!/bin/sh
# Git pre-commit hook that runs multiple hooks specified in $HOOKS.
# Make sure this script is executable. Bypass hooks with git commit --no-verify.
# This file is part of a set of unofficial pre-commit hooks available
# at github.
# Link: https://github.com/githubbrowser/Pre-commit-hooks
# Contact: David Martin, david.martin.mailbox@googlemail.com
###########################################################
# CONFIGURATION:
# pre-commit hooks to be executed. They should be in the same .git/hooks/ folder
# as this script. Hooks should return 0 if successful and nonzero to cancel the
# commit. They are executed in the order in which they are listed.
HOOKS="pre-commit-gdformat"
HOOKS="pre-commit-clang-format"
###########################################################
# There should be no need to change anything below this line.
. "$(dirname -- "$0")/canonicalize_filename.sh"
# exit on error
set -e
# Absolute path to this script, e.g. /home/user/bin/foo.sh
SCRIPT="$(canonicalize_filename "$0")"
# Absolute path this script is in, thus /home/user/bin
SCRIPTPATH="$(dirname -- "$SCRIPT")"
for hook in $HOOKS
do
echo "Running hook: $hook"
# run hook if it exists
# if it returns with nonzero exit with 1 and thus abort the commit
if [ -f "$SCRIPTPATH/$hook" ]; then
"$SCRIPTPATH/$hook"
if [ $? != 0 ]; then
exit 1
fi
else
echo "Error: file $hook not found."
echo "Aborting commit. Make sure the hook is in $SCRIPTPATH and executable."
echo "You can disable it by removing it from the list in $SCRIPT."
echo "You can skip all pre-commit hooks with --no-verify (not recommended)."
exit 1
fi
done

View file

@ -0,0 +1,148 @@
#! /usr/bin/env nix-shell
#! nix-shell -i sh -p clang
# git pre-commit hook that runs a clang-format stylecheck.
# Features:
# - abort commit when commit does not comply with the style guidelines
# - create a patch of the proposed style changes
# Modifications for clang-format by rene.milk@wwu.de
# This file is part of a set of unofficial pre-commit hooks available
# at github.
# Link: https://github.com/githubbrowser/Pre-commit-hooks
# Contact: David Martin, david.martin.mailbox@googlemail.com
# Some quality of life modifications made for Godot Engine.
##################################################################
# SETTINGS
# Set path to clang-format binary
# CLANG_FORMAT="/usr/bin/clang-format"
CLANG_FORMAT=`which clang-format`
# Remove any older patches from previous commits. Set to true or false.
# DELETE_OLD_PATCHES=false
DELETE_OLD_PATCHES=false
# Only parse files with the extensions in FILE_EXTS. Set to true or false.
# If false every changed file in the commit will be parsed with clang-format.
# If true only files matching one of the extensions are parsed with clang-format.
# PARSE_EXTS=true
PARSE_EXTS=true
# File types to parse. Only effective when PARSE_EXTS is true.
# FILE_EXTS=".c .h .cpp .hpp"
FILE_EXTS=".c .h .cpp .hpp .cc .hh .cxx .m .mm .inc .java .glsl"
# Use pygmentize instead of cat to parse diff with highlighting.
# Install it with `pip install pygments` (Linux) or `easy_install Pygments` (Mac)
# READER="pygmentize -l diff"
READER=cat
##################################################################
# There should be no need to change anything below this line.
. "$(dirname -- "$0")/canonicalize_filename.sh"
# exit on error
set -e
# check whether the given file matches any of the set extensions
matches_extension() {
local filename=$(basename "$1")
local extension=".${filename##*.}"
local ext
for ext in $FILE_EXTS; do [[ "$ext" == "$extension" ]] && return 0; done
return 1
}
# necessary check for initial commit
if git rev-parse --verify HEAD >/dev/null 2>&1 ; then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
if [ ! -x "$CLANG_FORMAT" ] ; then
printf "Error: clang-format executable not found.\n"
printf "Set the correct path in $(canonicalize_filename "$0").\n"
exit 1
fi
# create a random filename to store our generated patch
prefix="pre-commit-clang-format"
suffix="$(date +%s)"
patch="/tmp/$prefix-$suffix.patch"
# clean up any older clang-format patches
$DELETE_OLD_PATCHES && rm -f /tmp/$prefix*.patch
# create one patch containing all changes to the files
git diff-index --cached --diff-filter=ACMR --name-only $against -- | while read file;
do
# ignore thirdparty files
if grep -q "thirdparty" <<< $file; then
continue;
fi
# ignore file if we do check for file extensions and the file
# does not match any of the extensions specified in $FILE_EXTS
if $PARSE_EXTS && ! matches_extension "$file"; then
continue;
fi
# clang-format our sourcefile, create a patch with diff and append it to our $patch
# The sed call is necessary to transform the patch from
# --- $file timestamp
# +++ - timestamp
# to both lines working on the same file and having a/ and b/ prefix.
# Else it can not be applied with 'git apply'.
"$CLANG_FORMAT" -style=file "$file" | \
diff -u "$file" - | \
sed -e "1s|--- |--- a/|" -e "2s|+++ -|+++ b/$file|" >> "$patch"
done
# if no patch has been generated all is ok, clean up the file stub and exit
if [ ! -s "$patch" ] ; then
printf "Files in this commit comply with the clang-format rules.\n"
rm -f "$patch"
exit 0
fi
# a patch has been created, notify the user and exit
printf "\nThe following differences were found between the code to commit "
printf "and the clang-format rules:\n\n"
$READER "$patch"
printf "\n"
# Allows us to read user input below, assigns stdin to keyboard
exec < /dev/tty
while true; do
read -p "Do you want to apply that patch (Y - Apply, N - Do not apply, S - Apply and stage files)? [Y/N/S] " yn
case $yn in
[Yy] ) git apply $patch;
printf "The patch was applied. You can now stage the changes and commit again.\n\n";
break
;;
[Nn] ) printf "\nYou can apply these changes with:\n git apply $patch\n";
printf "(may need to be called from the root directory of your repository)\n";
printf "Aborting commit. Apply changes and commit again or skip checking with";
printf " --no-verify (not recommended).\n\n";
break
;;
[Ss] ) git apply $patch;
git diff-index --cached --diff-filter=ACMR --name-only $against -- | while read file;
do git add $file;
done
printf "The patch was applied and the changed files staged. You can now commit.\n\n";
break
;;
* ) echo "Please answer yes or no."
;;
esac
done
exit 1 # we don't commit in any case

23
misc/hooks/pre-commit-gdformat Executable file
View file

@ -0,0 +1,23 @@
#! /usr/bin/env nix-shell
#! nix-shell -i sh -p python38
GDTOOLKIT_VERSION=f5e2746d146200ec07ac6acb6fb378fd4c64f3f0
FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep '\.gd$' | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0
# Setup GDScript Toolkit.
if [ ! -f .venv/bin/activate ] || ! source .venv/bin/activate; then
python -m venv .venv && source .venv/bin/activate;
fi
if ! gdformat --version; then
pip install git+git://github.com/Scony/godot-gdscript-toolkit@${gdtoolkit_version};
fi
# Format all selected files.
echo "$FILES" | xargs gdformat
# Add back the formatted files to staging.
echo "$FILES" | xargs git add
exit 0