Skip to content

Commit

Permalink
add ruff linter in CI
Browse files Browse the repository at this point in the history
  • Loading branch information
cyrilus committed Jan 10, 2025
1 parent 17f623e commit ee6958a
Show file tree
Hide file tree
Showing 28 changed files with 133 additions and 215 deletions.
8 changes: 8 additions & 0 deletions .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
name: Ruff
on: [ push, pull_request ]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/ruff-action@v3
2 changes: 1 addition & 1 deletion .github/workflows/unittest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
fetch-depth: 0

Expand Down
8 changes: 1 addition & 7 deletions API/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,14 @@
Copyright (C) 2023 Probesys
"""

from flask import *
from flask import Response, send_file

import lotemplate as ot

import configargparse as cparse
import glob
import os
import sys
import shlex, subprocess
from time import sleep
from typing import Union
from zipfile import ZipFile
import random
import pdb

host='localhost'
port='200'
Expand Down
14 changes: 6 additions & 8 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@
Copyright (C) 2023 Probesys
"""

from flask import *
from flask import Flask,request, jsonify,after_this_request,send_file
from werkzeug.utils import secure_filename

import os

import hashlib
from shutil import copyfile, rmtree
import pdb
from os.path import isfile, join
from os import listdir
from API import utils
Expand All @@ -22,7 +20,7 @@
def main_route():
if request.headers.get('secretkey', '') != os.environ.get('SECRET_KEY', ''):
return utils.error_sim(
'ApiError', 'invalid_secretkey', f"The secret key is invalid or not given", {'key': 'secret_key'}), 401
'ApiError', 'invalid_secretkey', "The secret key is invalid or not given", {'key': 'secret_key'}), 401
if request.method == 'PUT':
if 'directory' not in request.headers:
return utils.error_sim(
Expand All @@ -43,7 +41,7 @@ def main_route():
def directory_route(directory):
if request.headers.get('secretkey', '') != os.environ.get('SECRET_KEY', ''):
return utils.error_sim(
'ApiError', 'invalid_secretkey', f"The secret key is invalid or not given", {'key': 'secret_key'}), 401
'ApiError', 'invalid_secretkey', "The secret key is invalid or not given", {'key': 'secret_key'}), 401
if not os.path.isdir(f"uploads/{directory}") and request.method != 'PUT':
return utils.error_sim(
'ApiError', 'dir_not_found', f"the specified directory {repr(directory)} doesn't exist",
Expand Down Expand Up @@ -96,12 +94,12 @@ def delete_image(response):
if request.method == 'POST':
try:
os.remove(file)
except Exception as ex:
except Exception:
print("Error delete file " + str(file))
return response
if request.headers.get('secretkey', '') != os.environ.get('SECRET_KEY', ''):
return utils.error_sim(
'ApiError', 'invalid_secretkey', f"The secret key is invalid or not given", {'key': 'secret_key'}), 401
'ApiError', 'invalid_secretkey', "The secret key is invalid or not given", {'key': 'secret_key'}), 401
if not os.path.isdir(f"uploads/{directory}"):
return utils.error_sim(
'ApiError', 'dir_not_found', f"the specified directory {repr(directory)} doesn't exist",
Expand Down Expand Up @@ -145,7 +143,7 @@ def delete_image(response):
def download_route(directory, file):
if request.headers.get('secretkey', '') != os.environ.get('SECRET_KEY', ''):
return utils.error_sim(
'ApiError', 'invalid_secretkey', f"The secret key is invalid or not given", {'key': 'secret_key'}), 401
'ApiError', 'invalid_secretkey', "The secret key is invalid or not given", {'key': 'secret_key'}), 401
if not os.path.isdir(f"uploads/{directory}"):
return utils.error_sim(
'ApiError', 'dir_not_found', f"the specified directory {repr(directory)} doesn't exist",
Expand Down
17 changes: 2 additions & 15 deletions lotemplate/CalcTemplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,15 @@
__all__ = (
'CalcTemplate',
)
import os
from typing import Union
from sorcery import dict_of


import uno
import unohelper
from com.sun.star.beans import PropertyValue
from com.sun.star.io import IOException
from com.sun.star.lang import IllegalArgumentException, DisposedException
from com.sun.star.connection import NoConnectException
from com.sun.star.uno import RuntimeException
from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
from com.sun.star.style.BreakType import PAGE_AFTER

from . import errors
from .utils import *

from lotemplate.Statement.CalcTableStatement import CalcTableStatement
from . import Template
from .Template import Template
from lotemplate.Statement.CalcSearchStatement import CalcTextStatement
import pdb
from jsondiff import diff

class CalcTemplate(Template):
Expand Down Expand Up @@ -80,7 +67,7 @@ def scan(self, **kwargs) -> dict[str: dict[str, Union[str, list[str]]]]:
:return: list containing all the variables founded in the template
"""

should_close = kwargs.get("should_close", False)
#should_close = kwargs.get("should_close", False)
texts = {}
#(Pdb) self.doc.getSheets().getElementNames()
for sheet in self.doc.getSheets():
Expand Down
4 changes: 1 addition & 3 deletions lotemplate/Statement/CalcSearchStatement.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import re
from com.sun.star.lang import XComponent
from com.sun.star.beans import PropertyValue, UnknownPropertyException
import regex
import pdb

class CalcTextStatement:
text_regex_str = r'\$(\w+(\(((?:\\.|.)*?)\))?)'
Expand Down Expand Up @@ -65,7 +63,7 @@ def fill(doc: XComponent, variable: str, value: str) -> None:
search = doc.createReplaceDescriptor()
search.SearchString = variable
search.ReplaceString = value
founded = doc.replaceAll(search)
doc.replaceAll(search)



15 changes: 6 additions & 9 deletions lotemplate/Statement/CalcTableStatement.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
from com.sun.star.lang import XComponent
from com.sun.star.uno import RuntimeException
from typing import Union
import lotemplate.errors as errors
from lotemplate.Statement.CalcSearchStatement import CalcTextStatement
from com.sun.star.sheet.CellInsertMode import NONE, DOWN, RIGHT, ROWS,COLUMNS
from com.sun.star.sheet.CellInsertMode import DOWN, RIGHT
from com.sun.star.sheet.CellDeleteMode import UP, LEFT
import re
import pdb


def incr_chr(c):
Expand All @@ -26,7 +23,7 @@ class CalcTableStatement:
table_pattern = re.compile("^table_[udlr]_(.+)",re.IGNORECASE)

def isTableVar(var):
if mymatch := re.match(CalcTableStatement.table_pattern,var):
if re.match(CalcTableStatement.table_pattern,var):
return True
else:
return False
Expand All @@ -51,9 +48,8 @@ def scan_range(myrange) -> None:
nonlocal doc
return CalcTextStatement.scan(myrange,True)
tab_vars = {}
table_vars = {}
for NamedRange in doc.NamedRanges:
if mymatch := re.match(CalcTableStatement.table_pattern,NamedRange.getName()):
if re.match(CalcTableStatement.table_pattern,NamedRange.getName()):
named = scan_range(NamedRange)
tab_vars[NamedRange.getName()] = {'type': 'object', 'value': named}

Expand All @@ -69,9 +65,10 @@ def fill(doc: XComponent, variable: str, value) -> None:
:return: None
"""
myrange=doc.NamedRanges.getByName(variable)
mycellrange=myrange.getReferredCells()
#mycellrange=myrange.getReferredCells()
mycellrangeaddr=myrange.getReferredCells().getRangeAddress()


mycontent,finalcol,finalrow =myrange.getContent().rsplit('$', 2)

StartColumn=myrange.getReferredCells().getRangeAddress().StartColumn
Expand Down Expand Up @@ -103,7 +100,7 @@ def fill(doc: XComponent, variable: str, value) -> None:
except IndexError:
CalcTextStatement.fill(rangetocopy,'&'+key,"")

if left==True:
if left:
myrange.setContent(mycontent+'$'+incr_str(finalcol,maxlen*size)+'$'+finalrow)
mycellrangeaddr.EndColumn=mycellrangeaddr.EndColumn+maxlen*size
mycellrangeaddr.StartColumn=mycellrangeaddr.StartColumn+maxlen*size
Expand Down
22 changes: 11 additions & 11 deletions lotemplate/Statement/CounterStatement.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@ def scan_counter(doc: XComponent) -> None:
scan for counter statement. No return. We just verify that there is
and endif for each if statement
"""
def compute_counter(x_found):
"""
Compute the counter statement.
"""
counter_text = x_found.getText()
counter_cursor = counter_text.createTextCursorByRange(x_found)
cursor_statement = CounterStatement(counter_cursor.String)
#def compute_counter(x_found):
# """
# Compute the counter statement.
# """
# counter_text = x_found.getText()
#counter_cursor = counter_text.createTextCursorByRange(x_found)
#cursor_statement = CounterStatement(counter_cursor.String)

def find_counter_to_compute(doc, search, x_found):
"""
Expand All @@ -70,7 +70,7 @@ def find_counter_to_compute(doc, search, x_found):
if x_found is None:
return None

compute_counter(x_found)
# compute_counter(x_found)

# searching for the next counter statement.
x_found_after = doc.findNext(x_found.End, search)
Expand Down Expand Up @@ -139,9 +139,9 @@ def find_counter_to_compute(doc, search, x_found):
if x_found is None:
return None

text = x_found.getText()
cursor = text.createTextCursorByRange(x_found)
str = cursor.String
#text = x_found.getText()
#cursor = text.createTextCursorByRange(x_found)
#str = cursor.String


compute_counter(x_found)
Expand Down
2 changes: 1 addition & 1 deletion lotemplate/Statement/ForStatement.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def scan_single_for(doc: XComponent, local_x_found) -> str:
scan for a single for statement
"""
for_statement = ForStatement(local_x_found.getString())
position_in_text = len(for_statement.for_string)
#position_in_text = len(for_statement.for_string)

endfor_search = doc.createSearchDescriptor()
endfor_search.SearchString = ForStatement.end_regex
Expand Down
9 changes: 4 additions & 5 deletions lotemplate/Statement/HtmlStatement.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import re
from sorcery import dict_of
import lotemplate.errors as errors
from com.sun.star.lang import XComponent
Expand All @@ -24,7 +23,7 @@ def scan_single_html(local_x_found) -> None:
"""
scan for a single for statement
"""
html_statement = HtmlStatement(local_x_found.getString())
#html_statement = HtmlStatement(local_x_found.getString())
endhtml_search = doc.createSearchDescriptor()
endhtml_search.SearchString = HtmlStatement.end_regex
endhtml_search.SearchRegularExpression = True
Expand All @@ -34,7 +33,7 @@ def scan_single_html(local_x_found) -> None:
cursor = local_x_found.getText().createTextCursorByRange(local_x_found)
raise errors.TemplateError(
'no_endhtml_found',
f"The statement [html] has no endhtml",
"The statement [html] has no endhtml",
dict_of(cursor.String)
)

Expand All @@ -55,7 +54,7 @@ def html_replace(template, doc: XComponent) -> None:
"""

def compute_html(doc, local_x_found):
html_statement = HtmlStatement(local_x_found.getString())
#html_statement = HtmlStatement(local_x_found.getString())
endhtml_search = doc.createSearchDescriptor()
endhtml_search.SearchString = HtmlStatement.end_regex
endhtml_search.SearchRegularExpression = True
Expand All @@ -65,7 +64,7 @@ def compute_html(doc, local_x_found):
cursor = local_x_found.getText().createTextCursorByRange(local_x_found)
raise errors.TemplateError(
'no_endhtml_found',
f"The statement [html] has no endhtml",
"The statement [html] has no endhtml",
dict_of(cursor.String)
)

Expand Down
2 changes: 1 addition & 1 deletion lotemplate/Statement/IfStatement.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def find_if_to_compute(doc, search, x_found):
if match is not None:
raise errors.TemplateError(
'too_many_endif_found',
f"The document has too many endif",
"The document has too many endif",
{}
)

Expand Down
2 changes: 1 addition & 1 deletion lotemplate/Statement/ImageStatement.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from com.sun.star.beans import PropertyValue, UnknownPropertyException
from com.sun.star.beans import PropertyValue
from com.sun.star.lang import XComponent
import regex
from urllib import request
Expand Down
2 changes: 1 addition & 1 deletion lotemplate/Statement/TableStatement.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def scan_cell(cell) -> None:
except errors.TemplateError as e:
raise e
continue
except RuntimeException as e:
except RuntimeException:
continue

return list_tab_vars if get_list else tab_vars
Expand Down
2 changes: 1 addition & 1 deletion lotemplate/Statement/TextStatement.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import re
from com.sun.star.lang import XComponent
from com.sun.star.beans import PropertyValue, UnknownPropertyException
from com.sun.star.beans import UnknownPropertyException
import regex
from lotemplate.Statement.ForStatement import ForStatement
from lotemplate.Statement.TableStatement import TableStatement
Expand Down
20 changes: 4 additions & 16 deletions lotemplate/Template.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,32 +12,20 @@
import os
from typing import Union
from sorcery import dict_of
import uno
import unohelper
from com.sun.star.beans import PropertyValue
from com.sun.star.io import IOException
from com.sun.star.lang import IllegalArgumentException, DisposedException
from com.sun.star.connection import NoConnectException
from com.sun.star.uno import RuntimeException
from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
from com.sun.star.style.BreakType import PAGE_AFTER

from . import errors
from . import Connexion
from .utils import *
#from . import Connexion
from .utils import get_file_url,get_cached_json

from lotemplate.Statement.ForStatement import ForStatement
from lotemplate.Statement.HtmlStatement import HtmlStatement
from lotemplate.Statement.IfStatement import IfStatement
from lotemplate.Statement.TextStatement import TextStatement
from lotemplate.Statement.TableStatement import TableStatement
from lotemplate.Statement.ImageStatement import ImageStatement
from lotemplate.Statement.CounterStatement import CounterManager

import uuid
import shutil
import json
import pdb


class Template:
Expand Down Expand Up @@ -95,7 +83,7 @@ def open_doc_from_url(self):
def validDocType(self,doc):
pass

def __init__(self, file_path: str, cnx: Connexion, should_scan: bool, json_cache_dir=None):
def __init__(self, file_path: str, cnx, should_scan: bool, json_cache_dir=None):
"""
An object representing a LibreOffice/OpenOffice template that you can fill, scan, export and more
Expand Down Expand Up @@ -124,7 +112,7 @@ def __init__(self, file_path: str, cnx: Connexion, should_scan: bool, json_cache
with open(cachedjson) as f:
self.variables = json.load(f)
return
except:
except Exception:
pass
self.variables = self.scan(should_close=True)
if json_cache_dir:
Expand Down
Loading

0 comments on commit ee6958a

Please # to comment.