Skip to content

Commit

Permalink
Add auto delete freopen (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
ste1hi authored May 9, 2024
1 parent 948cfbc commit 636ffde
Show file tree
Hide file tree
Showing 9 changed files with 255 additions and 147 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,5 @@ cython_debug/
#.idea/

token
*.html
*.html
.vscode
82 changes: 60 additions & 22 deletions OiRunner/BetterRunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import argparse
import sys
import os
import re
import shutil
import time
from typing import Optional
Expand All @@ -23,10 +24,10 @@ def _modify_file(self, file_name: str, file_type: str) -> int:
file_type -- The filename extension of input file.
Returns:
i -- Number of output files.
i -- Number of output files.
Raise:
SystemExit -- The file is empty.
SystemExit -- The file is empty.
'''
i = 1
a = ""
Expand All @@ -35,6 +36,7 @@ def _modify_file(self, file_name: str, file_type: str) -> int:
os.mkdir("~tmp")
with open(file_name, "r") as f:
for line in f:
file_path = os.path.join("~tmp", f"{i}.{file_type}")
flag = 1
if line.rstrip():
a += f"{line}"
Expand All @@ -43,8 +45,8 @@ def _modify_file(self, file_name: str, file_type: str) -> int:
print(f"error:{file_name} is empty.")
shutil.rmtree("~tmp")
sys.exit()
with open(f"~tmp/{i}.{file_type}", "w") as _f:
_f.write(a)
with open(file_path, "w") as f:
f.write(a)
i += 1
a = ""
if not flag:
Expand All @@ -53,27 +55,52 @@ def _modify_file(self, file_name: str, file_type: str) -> int:
sys.exit()

if a:
with open(f"~tmp/{i}.{file_type}", "w") as _f:
_f.write(a)
file_path = os.path.join("~tmp", f"{i}.{file_type}")
with open(file_path, "w") as f:
f.write(a)
return i

def _output(self, num: int, opt_file: str) -> None:
'''
Merge and output the split files.
Args:
num -- The number of files to merge.
opt_file -- Output file name.
num -- The number of files to merge.
opt_file -- Output file name.
'''
a = ""
for file_num in range(1, num+1):
a += f"#{file_num}:\n"
with open(f"~tmp/{file_num}.out", "r") as _f:
for line in _f:
out_file = os.path.join("~tmp", f"{file_num}.out")
with open(out_file, "r") as f:
for line in f:
a += f"{line}"

with open(opt_file, "w") as _out:
_out.write(a)
with open(opt_file, "w") as out:
out.write(a)

def delete_freopen(self, path: str) -> None:
'''
Delete freopen command.
Args:
path -- The cpp file path.
'''
if not os.path.exists(path):
raise ValueError("File not exists.")

with open(path, "r") as file:
content = file.read()

back_file_path = os.path.join(os.path.dirname(path), os.path.basename(path) + ".bak")
shutil.copy2(path, back_file_path)

re_match = r'freopen(\s)*\((\s)*"(\w)*\.{0,1}(\w)*"(\s)*,(\s)*"\w"(\s)*,(\s)*std\w{2,3}(\s)*\)(\s)*[,|;]'
changed_content = re.sub(re_match, "", content)

with open(path, "w") as file:
file.write(changed_content)


class BetterRunner:
Expand All @@ -94,6 +121,7 @@ def cmd_parse(self) -> None:
pa.add_argument("-of", "--outputfile", default="out.txt", help="Output file name.")
pa.add_argument("-af", "--answerfile", default="ans.txt", help="Answer file name.")
pa.add_argument("-g", "--gdb", action="store_true", help="Whether to debug via gdb when the answer is incorrect.")
pa.add_argument("-f", "--freopen", action="store_true", help="Add or delete freopen command.")
pa.add_argument("-d", "--directgdb", action="store_true", help="Directly using gdb for debugging.")
pa.add_argument("--onlyinput", action="store_true", help="Using file input (invalid for - j).")
pa.add_argument("--onlyoutput", action="store_true", help="Using file output (invalid when - j).")
Expand All @@ -111,7 +139,7 @@ def compile(self) -> None:
Compile files and generate executable files.
Raise:
SystemExit -- Compilation failed.
SystemExit -- Compilation failed.
'''
try:
compile = sp.Popen(["g++", self.args.filename + ".cpp", "-g", "-o", self.args.name])
Expand All @@ -133,18 +161,20 @@ def _check(self, opt_file: str, ipt_file: str, ans_file: str,
Local evaluation and get results.
Args:
opt_file -- Output file name.
opt_file -- Output file name.
ipt_file -- Input file name.
ipt_file -- Input file name.
ans_file -- Answer file name.
ans_file -- Answer file name.
file_num -- File number.
file_num -- File number.
run_file -- Executable file name (None means use the value of the command line parameter).
if_print -- Whether to output (None means use the value of the command line parameter).
run_file -- Executable file name (None means use the value of the command line parameter).
if_print -- Whether to output (None means use the value of the command line parameter).
Return:
if_pass -- Whether to pass the test.
if_pass -- Whether to pass the test.
'''

print(f"#{file_num}:")
Expand Down Expand Up @@ -204,6 +234,9 @@ def run(self) -> None:
gdb.wait()
sys.exit()

if not self.args.judge and self.args.freopen:
self.func.delete_freopen(self.args.filename + ".cpp")

if self.args.judge:
flag = 0

Expand All @@ -213,15 +246,20 @@ def run(self) -> None:
i = self.func._modify_file(self.answer_file, "ans")

for file_num in range(1, i + 1):
judge = self._check(f"~tmp/{file_num}.out", f"~tmp/{file_num}.in", f"~tmp/{file_num}.ans",
file_num)
out_file = os.path.join("~tmp", f"{file_num}.out")
in_file = os.path.join("~tmp", f"{file_num}.in")
ans_file = os.path.join("~tmp", f"{file_num}.ans")
judge = self._check(out_file, in_file, ans_file, file_num)
if not judge:
flag += 1

print(f"#final:Accuracy{((i - flag) / i): .2%}")
self.func._output(i, self.output_file)
shutil.rmtree("~tmp")

if flag == 0 and self.args.freopen:
self.func.delete_freopen(self.args.filename + ".cpp")

if self.args.gdb and flag > 0:
gdb = sp.Popen(["gdb", self.args.name])
gdb.wait()
Expand Down
31 changes: 30 additions & 1 deletion docs/automation.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,33 @@ When this feature is enabled, the program will get input from standard input sto
The default output file is `out.txt`.You can change it by `--outputfile` flag. [See details](judge.md#file-directory-structure)

## Auto gdb
Add `-d` or `--directgdb` will start gdb to debug the program directly.
Add `-d` or `--directgdb` will start gdb to debug the program directly.

## Auto delete freopen command
Add `-f` of `--freopen` to enable auto delete `freopen` command.

> [!WARNING]
> This feature will modify your program file in disk. Use this flag carefully, though you have a backup file.
During modification, the backup file will be created in the same directory, named `<program file name>.bak`.

This feature only support the freopen function call that is directly written in the `main()`.

The form like below is supported:
```c++
freopen
("file name" , "r" , stdin), // Supports line breaks and blanks.

freopen("file name", "w", stdout);
```
The form like below is unsupported:
```c++
#define fre(file_name) freopen(file_name, "w", stdout) // Presented in a #define form.
void fre(char file_name){
freopen(file_name, "w", stdout); // Nested function call.
}
```
When your code contains unsupported form, use `-f` flag might lead to unexpected outcomes.

When use this flag without `-j`, the package will modify your program file directly.With `-j`, the package will modify your program file after all test cases were passed.
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ name = "OiRunner"
authors = [{name = "ste1", email = "[email protected]"}]
description = "This package is designed to help oier compile the cpp file conveniently."
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.6"
license = {file = "LICENSE"}
dynamic = ["version"]
classifiers = [
Expand All @@ -17,5 +17,8 @@ classifiers = [
"Operating System :: Microsoft :: Windows",
]

[project.scripts]
oirun = "OiRunner.BetterRunner:main"

[tool.setuptools.dynamic]
version = {attr = "OiRunner.__version__"}
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
description = 'This package is designed to help oier compile the cpp file conveniently.',
url = 'https://github.com/ste1hi/OiRunner',
packages = find_packages(),
python_requires = '>=3.8',
python_requires = '>=3.6',
include_package_data = True,
entry_points={
'console_scripts': [
Expand Down
13 changes: 13 additions & 0 deletions tests/data/test_freopen/test_freopen.cpp.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#include <iostream>

using namespace std;

int main(){
freopen
("in", "r" , stdin),
freopen("out" , "w", stdout);

int a = 1;
cin >> a;
cout << a;
}
Loading

0 comments on commit 636ffde

Please sign in to comment.