11# Python Version: 3.x
2+ import distutils .version
23import functools
34import json
45import os
56import pathlib
7+ import shutil
68import subprocess
9+ import xml .etree .ElementTree as ET
710from logging import getLogger
8- from turtle import st
911from typing import *
10- import distutils .version
11- import shutil
12- import xml .etree .ElementTree as ET
1312
1413import onlinejudge_verify .languages .special_comments as special_comments
1514from onlinejudge_verify .languages .models import Language , LanguageEnvironment
@@ -34,15 +33,13 @@ def _check_dotnet_version() -> None:
3433@functools .lru_cache (maxsize = 1 )
3534def _check_expander_console () -> None :
3635 if not shutil .which ('dotnet-source-expand' ):
37- raise RuntimeError (
38- '`dotnet-source-expand` not in $PATH. Run `dotnet tool install -g SourceExpander.Console`' )
36+ raise RuntimeError ('`dotnet-source-expand` not in $PATH. Run `dotnet tool install -g SourceExpander.Console`' )
3937 command = ['dotnet-source-expand' , 'version' ]
4038 logger .info ('$ %s' , ' ' .join (command ))
4139 res = subprocess .check_output (command ).decode ().strip ()
4240 logger .info ('dotnet-source-expand version: %s' , res )
4341 if distutils .version .LooseVersion (res ) < distutils .version .LooseVersion ("5" ):
44- raise RuntimeError (
45- '`dotnet-source-expand` version must be 5.0.0 or newer. Update SourceExpander.Console. `dotnet tool update -g SourceExpander.Console`' )
42+ raise RuntimeError ('`dotnet-source-expand` version must be 5.0.0 or newer. Update SourceExpander.Console. `dotnet tool update -g SourceExpander.Console`' )
4643
4744
4845class EmbeddedLibrary :
@@ -58,7 +55,7 @@ def __repr__(self) -> str:
5855def _list_embedded (csproj_path : pathlib .Path ) -> List [EmbeddedLibrary ]:
5956 _check_expander_console ()
6057 if csproj_path is None or csproj_path .suffix != ".csproj" :
61- raise None
58+ raise RuntimeError ( 'csproj_path must be .csproj' )
6259 command = ['dotnet-source-expand' , 'library-list' , str (csproj_path )]
6360 logger .info ('$ %s' , ' ' .join (command ))
6461
@@ -68,10 +65,7 @@ def enumerate_library(lines: List[str]):
6865 if len (sp ) >= 2 :
6966 yield EmbeddedLibrary (sp [0 ], sp [1 ])
7067
71- res = list (enumerate_library (
72- subprocess .check_output (
73- command , encoding = 'utf-8'
74- ).strip ().splitlines ()))
68+ res = list (enumerate_library (subprocess .check_output (command , encoding = 'utf-8' ).strip ().splitlines ()))
7569 logger .debug ('libraries: %s' , res )
7670 return res
7771
@@ -83,8 +77,7 @@ def _check_embedded_existing(csproj_path: pathlib.Path) -> None:
8377 subprocess .check_output (command )
8478 l = _list_embedded (csproj_path )
8579 if len (l ) == 0 :
86- raise RuntimeError (
87- 'Library needs SourceExpander.Embedder' )
80+ raise RuntimeError ('Library needs SourceExpander.Embedder' )
8881
8982
9083def _check_env (path : pathlib .Path ):
@@ -97,8 +90,7 @@ def _check_env(path: pathlib.Path):
9790def _check_no_embedder (csproj_path : pathlib .Path ) -> None :
9891 root = ET .parse (csproj_path ).getroot ()
9992 if root .find ('.//PackageReference[@Include="SourceExpander.Embedder"]' ):
100- logger .error (
101- " Test project(%s) has `SourceExpander.Embedder` reference. Libraries and tests should not be in same project." , str (csproj_path ))
93+ logger .error (" Test project(%s) has `SourceExpander.Embedder` reference. Libraries and tests should not be in same project." , str (csproj_path ))
10294
10395
10496@functools .lru_cache (maxsize = None )
@@ -122,8 +114,7 @@ def _expand_code_dict(csproj_path: pathlib.Path) -> Dict[pathlib.Path, str]:
122114 command = ['dotnet-source-expand' , 'expand-all' , str (csproj_path )]
123115 logger .info ('$ %s' , ' ' .join (command ))
124116 json_res = subprocess .check_output (command )
125- return {pathlib .Path (t ['FilePath' ]): t ['ExpandedCode' ]
126- for t in json .loads (json_res )}
117+ return {pathlib .Path (t ['FilePath' ]): t ['ExpandedCode' ] for t in json .loads (json_res )}
127118
128119
129120@functools .lru_cache (maxsize = None )
@@ -150,14 +141,12 @@ def _dependency_info_list(csproj_path: pathlib.Path) -> List[DependencyInfo]:
150141 _check_expander_console ()
151142 _check_embedded_existing (csproj_path )
152143 if csproj_path is None or csproj_path .suffix != ".csproj" :
153- raise None
144+ raise RuntimeError ( 'csproj_path must be .csproj' )
154145
155146 command = ['dotnet-source-expand' , 'dependency' , '-p' , str (csproj_path )]
156147 logger .info ('$ %s' , ' ' .join (command ))
157148 res = subprocess .check_output (command )
158- return json .loads (
159- res ,
160- object_hook = lambda d : DependencyInfo (d ['FileName' ], d ['Dependencies' ], set (d ['TypeNames' ])))
149+ return json .loads (res , object_hook = lambda d : DependencyInfo (d ['FileName' ], d ['Dependencies' ], set (d ['TypeNames' ])))
161150
162151
163152@functools .lru_cache (maxsize = None )
@@ -174,62 +163,57 @@ def _dependency_info_dict(csproj_path: pathlib.Path) -> Dict[pathlib.Path, Depen
174163def _list_dependencies (path : pathlib .Path ) -> List [pathlib .Path ]:
175164 path = path .resolve ()
176165 depinfo = _dependency_info_dict (_resolve_csproj (path ))
177- return [p
178- for p in (
179- pathlib .Path (dep )
180- for dep in depinfo [path ].dependencies
181- ) if p .exists ()]
166+ return [p for p in (pathlib .Path (dep ) for dep in depinfo [path ].dependencies ) if p .exists ()]
182167
183168
184169@functools .lru_cache (maxsize = None )
185- def _get_target_framework (csproj_path : pathlib .Path ) -> bytes :
170+ def _get_target_framework (csproj_path : pathlib .Path ) -> str :
186171 root = ET .parse (csproj_path ).getroot ()
187172 target = root .findtext ('.//TargetFramework' )
173+ if target is None :
174+ raise RuntimeError ('<TargetFramework> is not found' )
188175 return target
189176
190177
191178class CSharpLanguageEnvironment (LanguageEnvironment ):
192179 @staticmethod
193180 def _create_runner_project (code : bytes , target_framework : str , output_dir ):
194181 os .makedirs (str (output_dir ), exist_ok = True )
195- with open (output_dir / 'runner.csproj' , 'w' ) as f :
182+ with open (output_dir / 'runner.csproj' , 'w' ) as f :
196183 f .write ('''<Project Sdk="Microsoft.NET.Sdk">
197184 <PropertyGroup>
198185 <OutputType>Exe</OutputType>
199186 <TargetFramework>{}</TargetFramework>
200187 </PropertyGroup>
201188</Project>''' .format (target_framework ))
202189
203- with open (output_dir / 'main.cs' , 'wb' ) as f :
190+ with open (output_dir / 'main.cs' , 'wb' ) as f :
204191 f .write (code )
205192
206193 def compile (self , path : pathlib .Path , * , basedir : pathlib .Path , tempdir : pathlib .Path ) -> None :
207194 path = path .resolve ()
208- output_dir = tempdir / 'dotnet'
195+ output_dir = tempdir / 'dotnet'
209196 _check_env (path )
210197 target_framework = _get_target_framework (_resolve_csproj (path ))
211198 logger .info ('build: TargetFramework = %s' , target_framework )
212- self ._create_runner_project (
213- _expand_code (path ), target_framework , output_dir )
199+ self ._create_runner_project (_expand_code (path ), target_framework , output_dir )
214200
215- command = ['dotnet' , 'build' , str (output_dir / 'runner.csproj' ),
216- '-c' , 'Release' ,
217- '-o' , str (output_dir / 'bin' )]
201+ command = ['dotnet' , 'build' , str (output_dir / 'runner.csproj' ), '-c' , 'Release' , '-o' , str (output_dir / 'bin' )]
218202 logger .info ('$ %s' , ' ' .join (command ))
219203 subprocess .check_output (command )
220204
221205 def get_execute_command (self , path : pathlib .Path , * , basedir : pathlib .Path , tempdir : pathlib .Path ) -> List [str ]:
222206 path = path .resolve ()
223- output_dir = tempdir / 'dotnet'
207+ output_dir = tempdir / 'dotnet'
224208 path = path .resolve ()
225209 _check_env (path )
226- return [str (output_dir / 'bin' / 'runner' )]
210+ return [str (output_dir / 'bin' / 'runner' )]
227211
228212
229213class CSharpLanguage (Language ):
230214 def list_attributes (self , path : pathlib .Path , * , basedir : pathlib .Path ) -> Dict [str , Any ]:
231215 path = path .resolve ()
232- attributes = special_comments .list_special_comments (path )
216+ attributes : Dict [ str , Any ] = special_comments .list_special_comments (path )
233217 attributes .setdefault ('links' , [])
234218 attributes ['links' ].extend (special_comments .list_embedded_urls (path ))
235219 return attributes
0 commit comments