1
0
mirror of https://gitlab.com/kelteseth/ScreenPlay.git synced 2024-11-22 02:32:29 +01:00

Fix all formatting scripts and format files

They default to format but also can be used
for checking
This commit is contained in:
Elias Steurer 2023-08-20 11:59:02 +02:00
parent 9b1de7cadf
commit e327f73812
29 changed files with 372 additions and 305 deletions

View File

@ -15,5 +15,6 @@ formatting:
- python -m pip install -U pip wheel --break-system-packages
- python -m pip install -U cmakelang --break-system-packages
- cd Tools
- python clang_format.py
- python cmake_format.py
- python check_format_cmake.py --check
- python check_format_cpp.py --check
- python check_format_qml.py --check

8
.vscode/tasks.json vendored
View File

@ -28,7 +28,7 @@
"cwd": "${workspaceFolder}/Tools"
},
"args": [
"clang_format.py"
"check_format_cpp.py"
]
},
{
@ -46,7 +46,7 @@
"cwd": "${workspaceFolder}/Tools"
},
"args": [
"cmake_format.py"
"check_format_cmake.py"
]
},
{
@ -64,7 +64,7 @@
"cwd": "${workspaceFolder}/Tools"
},
"args": [
"qml_format.py"
"check_format_qml.py"
]
},
{
@ -87,7 +87,7 @@
},
{
"type": "process",
"label": "Export ScreenPlay release, with deploy and steam enabled",
"label": "Build ScreenPlay release, with deploy and steam enabled",
"command": "python3",
"windows": {
"command": "python"

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: BSD-3-Clause
import QtQuick
import QtQuick.Layouts

View File

@ -42,19 +42,19 @@ Item {
anchors.fill: parent
hoverEnabled: true
Component.onCompleted: {
attractor.pointX = parent.width * .5
attractor.pointY = 0
attractor.pointX = parent.width * .5;
attractor.pointY = 0;
}
onPressed: {
attractor.enabled = true
attractor.enabled = true;
}
onPositionChanged: {
attractor.pointX = mouseX
attractor.pointY = mouseY
attractor.pointX = mouseX;
attractor.pointY = mouseY;
}
onReleased: {
attractor.enabled = false
attractor.enabled = false;
}
}

View File

@ -8,32 +8,31 @@ Item {
implicitHeight: 100
function timeChanged() {
var date = new Date
var hours = ""
var minutes = ""
var seconds = ""
var date = new Date;
var hours = "";
var minutes = "";
var seconds = "";
if (date.getHours() < 10) {
hours = "0" + date.getHours().toString()
hours = "0" + date.getHours().toString();
} else {
hours = date.getHours().toString()
hours = date.getHours().toString();
}
if (date.getMinutes() < 10) {
minutes = "0" + date.getMinutes().toString()
minutes = "0" + date.getMinutes().toString();
} else {
minutes = date.getMinutes().toString()
minutes = date.getMinutes().toString();
}
if (date.getSeconds() < 10) {
seconds = "0" + date.getSeconds().toString()
seconds = "0" + date.getSeconds().toString();
} else {
seconds = date.getSeconds().toString()
seconds = date.getSeconds().toString();
}
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
var day = days[date.getDay()]
var month = months[date.getMonth()]
txtClock.text = hours + ":" + minutes + ":" + seconds
txtDate.text = day + ", " + date.getDay(
) + " " + month + ", " + date.getFullYear()
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var day = days[date.getDay()];
var month = months[date.getMonth()];
txtClock.text = hours + ":" + minutes + ":" + seconds;
txtDate.text = day + ", " + date.getDay() + " " + month + ", " + date.getFullYear();
}
Timer {

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: BSD-3-Clause
import QtQuick
import QtQuick.Layouts
@ -17,16 +16,16 @@ Item {
property string link
property string mediaContent
onMediaContentChanged: {
print("src")
const src = parseItem(model.mediaContent, 'url="', '"')
print("src", src)
print("src");
const src = parseItem(model.mediaContent, 'url="', '"');
print("src", src);
//img.source = src;
}
function parseItem(raw, startTag, endTag) {
var startIdx = raw.indexOf(startTag) + startTag.length
var endIdx = raw.indexOf(endTag, startIdx)
return raw.substring(startIdx, endIdx)
var startIdx = raw.indexOf(startTag) + startTag.length;
var endIdx = raw.indexOf(endTag, startIdx);
return raw.substring(startIdx, endIdx);
}
RowLayout {
@ -49,8 +48,8 @@ Item {
MouseArea {
anchors.fill: parent
onClicked: {
print(model.category)
print(model.mediaContent)
print(model.category);
print(model.mediaContent);
//Qt.openUrlExternally(model.link);
}
}

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: BSD-3-Clause
import QtQuick
import QtQuick.Controls
@ -18,7 +17,7 @@ Item {
query: "/rss/channel/item"
onStatusChanged: {
if (status === XmlListModel.Error) {
console.log("Error: " + errorString)
console.log("Error: " + errorString);
}
}

View File

@ -12,41 +12,38 @@ Item {
property string pubDate
property string pubDateFormatted
onPubDateChanged: {
var date = new Date(pubDate)
root.pubDateFormatted = date.toLocaleDateString(
Qt.locale(),
"ddd, dd MMM yyyy") + ' ' + date.toLocaleTimeString(
Qt.locale(), "HH:mm:ss")
var date = new Date(pubDate);
root.pubDateFormatted = date.toLocaleDateString(Qt.locale(), "ddd, dd MMM yyyy") + ' ' + date.toLocaleTimeString(Qt.locale(), "HH:mm:ss");
}
property string description
onDescriptionChanged: {
print("description")
print("description");
// See https://hnrss.org/frontpage <description> content
// We need to manually parse it here to get the points and comments
points = parsePoints(description)
commentCount = parseCommentCount(description)
print(points, commentCount)
points = parsePoints(description);
commentCount = parseCommentCount(description);
print(points, commentCount);
}
function parseCommentCount(raw) {
var commentPrefix = "<p># Comments: "
var commentSuffix = "</p>"
var startIdx = raw.indexOf(commentPrefix)
var commentPrefix = "<p># Comments: ";
var commentSuffix = "</p>";
var startIdx = raw.indexOf(commentPrefix);
if (startIdx === -1)
return "N/A" // return "N/A" if comment count is not found in the description
startIdx += commentPrefix.length
var endIdx = raw.indexOf(commentSuffix, startIdx)
return raw.substring(startIdx, endIdx)
return "N/A"; // return "N/A" if comment count is not found in the description
startIdx += commentPrefix.length;
var endIdx = raw.indexOf(commentSuffix, startIdx);
return raw.substring(startIdx, endIdx);
}
function parsePoints(raw) {
var pointsPrefix = "<p>Points: "
var pointsSuffix = "</p>"
var startIdx = raw.indexOf(pointsPrefix)
var pointsPrefix = "<p>Points: ";
var pointsSuffix = "</p>";
var startIdx = raw.indexOf(pointsPrefix);
if (startIdx === -1)
return "N/A" // return "N/A" if points are not found in the description
startIdx += pointsPrefix.length
var endIdx = raw.indexOf(pointsSuffix, startIdx)
return raw.substring(startIdx, endIdx)
return "N/A"; // return "N/A" if points are not found in the description
startIdx += pointsPrefix.length;
var endIdx = raw.indexOf(pointsSuffix, startIdx);
return raw.substring(startIdx, endIdx);
}
RowLayout {
id: wrapper
@ -68,15 +65,14 @@ Item {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
onClicked: {
Qt.openUrlExternally(model.link)
Qt.openUrlExternally(model.link);
}
}
}
Text {
id: descriptionText
text: root.points + " Points • " + root.commentCount
+ " Comments 🔗 " + "• Published: " + root.pubDateFormatted
text: root.points + " Points • " + root.commentCount + " Comments 🔗 " + "• Published: " + root.pubDateFormatted
wrapMode: Text.WordWrap
font.pointSize: 10
opacity: .7
@ -85,7 +81,7 @@ Item {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
onClicked: {
Qt.openUrlExternally(model.commentsLink)
Qt.openUrlExternally(model.commentsLink);
}
}
}

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: BSD-3-Clause
import QtQuick
import QtQuick.Layouts
@ -44,7 +43,7 @@ Item {
}
}
onActivated: {
rssModel.source = combo.currentValue
rssModel.source = combo.currentValue;
}
}
ToolButton {
@ -79,10 +78,10 @@ Item {
source: combo.currentValue
query: "/rss/channel/item"
function load() {
print(":load")
var tempSource = rssModel.source
rssModel.source = ""
rssModel.source = tempSource
print(":load");
var tempSource = rssModel.source;
rssModel.source = "";
rssModel.source = tempSource;
}
XmlListModelRole {

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: BSD-3-Clause
import QtQuick
import QtQuick.Layouts
@ -28,11 +27,11 @@ Item {
}
function stringListToString(list) {
let out = ""
let out = "";
for (var i = 0; i < list.length; i++) {
out += "\n" + list[i]
out += "\n" + list[i];
}
return out
return out;
}
RowLayout {
@ -57,8 +56,7 @@ Item {
}
}
Text {
text: root.stringListToString(
ipAddress.privateIpV4AddressList)
text: root.stringListToString(ipAddress.privateIpV4AddressList)
color: root.accentColor
font {
pointSize: 16
@ -66,8 +64,7 @@ Item {
}
}
Text {
text: root.stringListToString(
ipAddress.privateIpV6AddressList)
text: root.stringListToString(ipAddress.privateIpV6AddressList)
color: root.accentColor
font {
pointSize: 16

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: BSD-3-Clause
import QtQuick
import QtQuick.Layouts
@ -20,56 +19,57 @@ Item {
id: weather
city: "Friedrichshafen"
onReady: {
rp.model = weather.days
rp.model = weather.days;
// Qt bug https://bugreports.qt.io/browse/QTBUG-105137
test()
test();
}
}
function test() {}
function test() {
}
function mapWeatherCode(code) {
const weather_time = ""
const weather_time = "";
// or "-day", "-night"
const weather_prefix = "wi" + weather_time + "-"
const weather_prefix = "wi" + weather_time + "-";
// https://open-meteo.com/en/docs
// WMO Weather interpretation codes (WW)
// to https://erikflowers.github.io/weather-icons/
switch (code) {
case 0:
return weather_prefix + "day-sunny"
return weather_prefix + "day-sunny";
case 1:
case 2:
case 3:
return weather_prefix + "cloud"
return weather_prefix + "cloud";
case 45:
case 48:
return weather_prefix + "day-sunny"
return weather_prefix + "day-sunny";
case 51:
case 53:
case 55:
return weather_prefix + "rain-mix"
return weather_prefix + "rain-mix";
case 61:
case 63:
case 65:
return weather_prefix + "rain-mix"
return weather_prefix + "rain-mix";
case 71:
case 73:
case 75:
return weather_prefix + "snow"
return weather_prefix + "snow";
case 77:
return weather_prefix + "snow"
return weather_prefix + "snow";
case 80:
case 81:
case 82:
return weather_prefix + "snow"
return weather_prefix + "snow";
case 85:
case 86:
return weather_prefix + "snow"
return weather_prefix + "snow";
case 95:
return weather_prefix + "thunderstorm"
return weather_prefix + "thunderstorm";
case 96:
case 99:
return weather_prefix + "storm-showers"
return weather_prefix + "storm-showers";
}
}
@ -89,9 +89,7 @@ Item {
Layout.alignment: Qt.AlignCenter
horizontalAlignment: Text.AlignHCenter
color: Material.primaryTextColor
text: "longtitude: " + weather.longtitude + " - latitude: "
+ weather.latitude + " - elevation: " + weather.elevation
+ "m - population: " + weather.population
text: "longtitude: " + weather.longtitude + " - latitude: " + weather.latitude + " - elevation: " + weather.elevation + "m - population: " + weather.population
}
RowLayout {
@ -129,8 +127,7 @@ Item {
}
Layout.alignment: Qt.AlignCenter
horizontalAlignment: Image.AlignHCenter
source: "qrc:/qml/ScreenPlayWeather/assets/icons/" + root.mapWeatherCode(
weatherCode) + ".svg"
source: "qrc:/qml/ScreenPlayWeather/assets/icons/" + root.mapWeatherCode(weatherCode) + ".svg"
}
TextItem {
text: "Weather Code"

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: BSD-3-Clause
import QtQuick
import QtQuick.Controls
@ -15,27 +14,27 @@ Item {
property int defaultHeight: 200
function request(url, callback) {
var xhr = new XMLHttpRequest()
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = (function (myxhr) {
return function () {
if (myxhr.readyState === 4)
callback(myxhr)
}
})(xhr)
xhr.open('GET', url)
xhr.send('')
callback(myxhr);
};
})(xhr);
xhr.open('GET', url);
xhr.send('');
}
Component.onCompleted: {
request("http://xkcd.com/info.0.json", function (o) {
if (o.status === 200) {
var d = eval('new Object(' + o.responseText + ')')
console.log(o.responseText)
img.source = d.img
var d = eval('new Object(' + o.responseText + ')');
console.log(o.responseText);
img.source = d.img;
} else {
console.log("Some error has occurred")
console.log("Some error has occurred");
}
})
});
}
Image {
@ -45,22 +44,22 @@ Item {
property size imgSize: Qt.size(root.defaultWidth, defaultHeight)
onStatusChanged: {
if (img.status !== Image.Ready)
return
return;
if (img.sourceSize.width === 0 || img.sourceSize.height === 0)
return
root.implicitWidth = img.sourceSize.width
root.implicitHeight = img.sourceSize.height
print(img.status, img.sourceSize.width, img.sourceSize.height)
img.imgSize = Qt.size(img.sourceSize.width, img.sourceSize.height)
print("img.size", img.imgSize)
return;
root.implicitWidth = img.sourceSize.width;
root.implicitHeight = img.sourceSize.height;
print(img.status, img.sourceSize.width, img.sourceSize.height);
img.imgSize = Qt.size(img.sourceSize.width, img.sourceSize.height);
print("img.size", img.imgSize);
}
}
MouseArea {
anchors.fill: parent
onClicked: {
root.state = root.state === "expanded" ? "normal" : "expanded"
print(root.state, root.implicitHeight, root.implicitWidth)
root.state = root.state === "expanded" ? "normal" : "expanded";
print(root.state, root.implicitHeight, root.implicitWidth);
}
}

View File

@ -11,17 +11,9 @@ Item {
implicitWidth: 240
implicitHeight: 120
property int totalHours: 24
property int remainingHours: Math.max(0, Math.floor(
(new Date().setHours(
24, 0, 0,
0) - new Date()) / 3600000))
property int totalDays: new Date(new Date().getFullYear() + 1, 0,
1) - new Date() / (24 * 60 * 60 * 1000)
property int remainingDays: Math.max(
0, Math.floor(
(new Date(new Date().getFullYear() + 1,
0,
1) - new Date()) / (24 * 60 * 60 * 1000)))
property int remainingHours: Math.max(0, Math.floor((new Date().setHours(24, 0, 0, 0) - new Date()) / 3600000))
property int totalDays: new Date(new Date().getFullYear() + 1, 0, 1) - new Date() / (24 * 60 * 60 * 1000)
property int remainingDays: Math.max(0, Math.floor((new Date(new Date().getFullYear() + 1, 0, 1) - new Date()) / (24 * 60 * 60 * 1000)))
Material.theme: Material.Dark
Material.accent: Material.DeepOrange
@ -50,11 +42,7 @@ Item {
running: true
repeat: true
onTriggered: {
remainingHours = Math.max(
0,
Math.floor((new Date().setHours(
24, 0, 0,
0) - new Date()) / 3600000))
remainingHours = Math.max(0, Math.floor((new Date().setHours(24, 0, 0, 0) - new Date()) / 3600000));
}
}
}
@ -81,11 +69,7 @@ Item {
running: true
repeat: true
onTriggered: {
remainingDays = Math.max(0,
Math.floor((new Date(new Date().getFullYear(
) + 1,
0, 1)
- new Date()) / (24 * 60 * 60 * 1000)))
remainingDays = Math.max(0, Math.floor((new Date(new Date().getFullYear() + 1, 0, 1) - new Date()) / (24 * 60 * 60 * 1000)));
}
}
}

View File

@ -138,6 +138,7 @@ set(RESOURCES
assets/icons/icon_close.svg
assets/icons/icon_code.svg
assets/icons/icon_community.svg
assets/icons/icon_contains_audio.svg
assets/icons/icon_delete.svg
assets/icons/icon_document.svg
assets/icons/icon_done.svg
@ -152,7 +153,6 @@ set(RESOURCES
assets/icons/icon_installed.svg
assets/icons/icon_launch.svg
assets/icons/icon_minimize.svg
assets/icons/icon_contains_audio.svg
assets/icons/icon_movie.svg
assets/icons/icon_new_releases.svg
assets/icons/icon_open_in_new.svg

View File

@ -175,7 +175,6 @@ Item {
}
}
Image {
id: icnType

View File

@ -82,7 +82,7 @@ Item {
isChecked: App.settings.showDefaultContent
onCheckboxChanged: function (checked) {
App.settings.setShowDefaultContent(checked);
App.installedListModel.reset()
App.installedListModel.reset();
}
}

View File

@ -186,8 +186,7 @@ void ScreenPlaySDK::ScreenPlaySDK::redirectMessageOutputToMainWindow(QtMsgType t
// Also redirect to regular output if we debug
// wallpaper or widgets directly
switch (type)
{
switch (type) {
case QtDebugMsg:
qDebug() << msg;
break;

View File

@ -49,7 +49,7 @@ Item {
onPlaybackStateChanged: {
if (mediaPlayer.playbackState == MediaPlayer.PlayingState && !fadeInDone) {
fadeInDone = true;
startTimer.start()
startTimer.start();
}
}
loops: root.loops ? MediaPlayer.Infinite : 1
@ -72,8 +72,7 @@ Item {
id: pauseTimer
interval: 100
onTriggered: {
mediaPlayer.pause()
mediaPlayer.pause();
}
}
Connections {
@ -97,11 +96,11 @@ Item {
function onVisualsPausedChanged(visualsPaused) {
if (!Wallpaper.isPlaying)
return
return;
if (visualsPaused)
pauseTimer.start()
pauseTimer.start();
else
mediaPlayer.play()
mediaPlayer.play();
}
target: Wallpaper

View File

@ -0,0 +1,56 @@
#!/usr/bin/python3
# SPDX-License-Identifier: LicenseRef-EliasSteurerTachiom OR AGPL-3.0-only
import os
import argparse
import util
from format_util import find_files
from format_util import execute_threaded
from sys import stdout
stdout.reconfigure(encoding='utf-8')
def format_file_function(file):
executable = "cmake-format"
if os.name == 'nt':
executable += ".exe"
os.system(" %s -c ../.cmake-format.py -i %s" % (executable, file))
print("Format: ", file)
def check_format_file_function(file):
executable = "cmake-format"
if os.name == 'nt':
executable += ".exe"
result = os.system(" %s -c ../.cmake-format.py --check %s" %
(executable, file))
# If the return code is non-zero, the file isn't formatted correctly
if result != 0:
print(f"{file} is not correctly formatted.")
return False
return True
def main(git_staged_only=False, check_only=False):
file_list = find_files(
('CMakeLists.txt', '*.cmake'), util.repo_root_path(), git_staged_only)
if check_only:
result = execute_threaded(file_list, check_format_file_function)
if not result: # Since result is a single boolean, you can directly check its value
print("Some files are not correctly formatted!")
exit(1)
else:
execute_threaded(file_list, format_file_function)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--stage-only', action="store_true", dest="stage_only", default=False,
help="Check/format only staged files")
parser.add_argument('-c', '--check', action="store_true", dest="check_only", default=False,
help="Only check if files are correctly formatted without actually formatting them")
args = parser.parse_args()
main(args.stage_only, args.check_only)

61
Tools/check_format_cpp.py Normal file
View File

@ -0,0 +1,61 @@
#!/usr/bin/python3
# SPDX-License-Identifier: LicenseRef-EliasSteurerTachiom OR AGPL-3.0-only
import os
import subprocess
import argparse
import util
from format_util import find_files
from format_util import execute_threaded
from sys import stdout
stdout.reconfigure(encoding='utf-8')
def format_file_function(file):
executable = "clang-format"
if os.name == 'nt':
executable = "clang-format.exe"
process = subprocess.run(" %s -style=file -i %s" %
(executable, file), capture_output=True, shell=True)
print("Format: %s \t return: %s" % (file, process.returncode))
def check_format_file_function(file):
executable = "clang-format"
if os.name == 'nt':
executable += ".exe"
result = subprocess.run(" %s -style=file --output-replacements-xml %s" %
(executable, file), capture_output=True, shell=True, text=True)
# Check for opening replacement tag with attributes (a space after it indicates attributes)
if "<replacement " in result.stdout:
print(f"{file} is not correctly formatted.")
print(f"{result.stdout} ")
return False
return True
def main(git_staged_only=False, check_only=False):
exclude_folders = ("ScreenPlayWorkshop/SteamSDK",
"ThirdParty", "build-x64-windows-release")
file_list = find_files(
('.cpp', '.h'), util.repo_root_path(), git_staged_only, exclude_folders)
if check_only:
result = execute_threaded(file_list, check_format_file_function)
if not result: # Since result is a single boolean, you can directly check its value
print("Some files are not correctly formatted!")
exit(1)
else:
execute_threaded(file_list, format_file_function)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--s', '--stage-only', action="store_true", dest="stage_only", default=False,
help="Check/format only staged files")
parser.add_argument('--c', '--check', action="store_true", dest="check_only", default=False,
help="Only check if files are correctly formatted without actually formatting them")
args = parser.parse_args()
main(args.stage_only, args.check_only)

86
Tools/check_format_qml.py Normal file
View File

@ -0,0 +1,86 @@
#!/usr/bin/python3
import os
import subprocess
import argparse
import util
import defines
import hashlib
from format_util import find_files
from format_util import execute_threaded
from sys import stdout, exit
import hashlib
import shutil
stdout.reconfigure(encoding='utf-8')
def format_qml_file(file):
executable = "qmlformat"
if os.name == 'nt':
executable = "qmlformat.exe"
qt_bin_path = defines.QT_BIN_PATH
executable = qt_bin_path.joinpath(executable)
# Add -i for formatting in place
process = subprocess.run(
[executable, "-i -l unix", file], capture_output=True, shell=True)
print("Format: %s \t return: %s" % (file, process.returncode))
def compute_md5(file_path):
"""Compute MD5 hash of the content of the given file."""
with open(file_path, 'rb') as f:
return hashlib.md5(f.read()).hexdigest()
def check_format_qml_file(file):
executable = "qmlformat"
if os.name == 'nt':
executable = "qmlformat.exe"
qt_bin_path = defines.QT_BIN_PATH
executable = qt_bin_path.joinpath(executable)
# Step 1: Copy the original file
backup_file = file + ".backup"
shutil.copy(file, backup_file)
# Step 2: Run qmlformat with in-place editing
subprocess.run([executable, "-i", file], check=True)
# Step 3: Compare MD5 hash of the original (backup) and the formatted file
original_hash = compute_md5(backup_file)
formatted_hash = compute_md5(file)
# Step 4: Remove the backup copy
os.remove(backup_file)
# Step 5: Return the comparison result
if original_hash != formatted_hash:
print(f"{file} is not correctly formatted.")
return False
return True
def main(git_staged_only=False, check_only=False):
exclude_folders = ("ThirdParty", "build-x64-windows-release")
file_list = find_files(('.qml'), util.repo_root_path(),
git_staged_only, exclude_folders)
if check_only:
result = execute_threaded(file_list, check_format_qml_file)
if not result:
print("Some files are not correctly formatted!")
exit(1)
else:
execute_threaded(file_list, format_qml_file)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--s', '--stage-only', action="store_true", dest="stage_only", default=False,
help="Check/format only staged files")
parser.add_argument('--c', '--check', action="store_true", dest="check_only", default=False,
help="Only check if files are correctly formatted without actually formatting them")
args = parser.parse_args()
main(args.stage_only, args.check_only)

View File

@ -1,36 +0,0 @@
#!/usr/bin/python3
# SPDX-License-Identifier: LicenseRef-EliasSteurerTachiom OR AGPL-3.0-only
import os
import subprocess
import argparse
from format_util import find_files
from format_util import check_git_exit
from format_util import execute_threaded
from sys import stdout
stdout.reconfigure(encoding='utf-8')
def format_file_function(file):
executable = "clang-format"
if os.name == 'nt':
executable = "clang-format.exe"
process = subprocess.run(" %s -style=file -i %s" %
(executable, file), capture_output=True, shell=True)
print("Format: %s \t return: %s" % (file, process.returncode))
def main(git_staged_only=False):
file_list = find_files(('.cpp', '.h'), "", git_staged_only)
execute_threaded(file_list, format_file_function)
if not git_staged_only:
check_git_exit("Clang Format")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', action="store_true", dest="stage_only",
default=False)
args = parser.parse_args()
main(args.stage_only)

View File

@ -1,31 +0,0 @@
#!/usr/bin/python3
# SPDX-License-Identifier: LicenseRef-EliasSteurerTachiom OR AGPL-3.0-only
import os
import argparse
from format_util import find_files
from format_util import check_git_exit
from format_util import execute_threaded
from sys import stdout
stdout.reconfigure(encoding='utf-8')
def format_file_function(file):
executable = "cmake-format"
if os.name == 'nt':
executable = "cmake-format.exe"
os.system(" %s -c ../.cmake-format.py -i %s" % (executable, file))
print("Format: ", file)
def main(git_staged_only=False):
file_list = find_files(('CMakeLists.txt'), "", git_staged_only)
execute_threaded(file_list, format_file_function)
if not git_staged_only:
check_git_exit("CMake Format")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', action="store_true", dest="stage_only",
default=False)
args = parser.parse_args()
main(args.stage_only)

View File

@ -3,6 +3,7 @@
import subprocess
import sys
import os
import util
from multiprocessing import cpu_count
from multiprocessing import Pool
from multiprocessing import dummy
@ -28,33 +29,38 @@ def find_all_git_staged_files():
return out
def find_files(file_endings_tuple, path="", git_staged_only=False):
def find_files(file_endings_tuple, path="", git_staged_only=False, exclude_folders=()):
file_list = []
# Get the root folder by moving one up
root = Path(__file__).parent.absolute()
root = os.path.abspath(os.path.join(root, "../"))
root = os.path.join(root, path)
print(root)
if git_staged_only:
file_list = find_all_git_staged_files()
file_list = find_all_git_staged_files() # Assuming you've defined this
else:
file_list = find_all_files(root)
for dirpath, dirnames, filenames in os.walk(path):
# Normalize the current directory path
norm_dirpath = os.path.normpath(dirpath)
filtered_file_list = []
for filename in file_list:
# Check if the current directory is to be excluded
if exclude_folders and any(os.path.normpath(excl_folder) in norm_dirpath for excl_folder in exclude_folders):
continue
for filename in filenames:
if filename.endswith(file_endings_tuple):
filtered_file_list.append(os.path.join(root, filename))
file_list.append(os.path.join(dirpath, filename))
return filtered_file_list
return file_list
def execute_threaded(file_list, format_file_function):
p = Pool(cpu_count())
p.map(format_file_function, file_list)
p.close()
p.join()
if not file_list:
return True # or False, depending on how you want to handle an empty list
with Pool(cpu_count()) as p:
results = p.map(format_file_function, file_list)
# Check if any result is False and return accordingly
if any(result is False for result in results):
return False
return True
def check_git_exit(caller_name):
@ -70,4 +76,3 @@ def check_git_exit(caller_name):
out.replace("\\n", "\n")
# print(out)
sys.exit(1)

View File

@ -1,40 +0,0 @@
#!/usr/bin/python3
# SPDX-License-Identifier: LicenseRef-EliasSteurerTachiom OR AGPL-3.0-only
import os
import subprocess
import argparse
import sys
import defines
from format_util import find_files
from format_util import check_git_exit
from format_util import execute_threaded
from sys import stdout
stdout.reconfigure(encoding='utf-8')
def format_file_function(file):
executable = "qmlformat"
if os.name == 'nt':
executable = "qmlformat.exe"
qt_bin_path = defines.QT_BIN_PATH
executable = qt_bin_path.joinpath(executable)
process = subprocess.run(
"%s -i %s" % (executable, file), capture_output=True, shell=True)
print("Format: %s \t return: %s" % (file, process.returncode))
def main(git_staged_only=False):
file_list = find_files(('.qml'), os.path.abspath(os.path.join(os.getcwd(), "../")), git_staged_only)
execute_threaded(file_list, format_file_function)
if not git_staged_only:
check_git_exit("QML Format")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', action="store_true", dest="stage_only",
default=False)
args = parser.parse_args()
main(args.stage_only)