1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
#![warn(missing_docs)]
#![warn(clippy::missing_docs_in_private_items)]
use std::{
fmt::Formatter,
hash::{
Hash,
Hasher,
},
io::Write,
path::PathBuf,
process::{
Command,
Output,
Stdio,
},
};
use anyhow::{
anyhow,
bail,
Context,
Result,
};
use futures::{
future::{
join_all,
try_join_all,
},
stream::FuturesUnordered,
};
use rhai::Array;
// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
use rhai::{
CustomType,
EvalAltResult,
};
use serde::{
Deserialize,
Serialize,
};
use snailquote::unescape;
use tokio::io::AsyncWriteExt;
use tree_sitter::{
Query,
QueryCursor,
Tree,
};
use umm_derive::generate_rhai_variant;
use crate::{
constants::*,
grade::{
JavacDiagnostic,
LineRef,
},
parsers::parser,
util::*,
vscode::{
self,
},
Dict,
};
/// Types of Java files -
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum FileType {
/// - Interface
Interface,
/// - Class
Class,
/// - Class with a main method
ClassWithMain,
/// - JUnit test class
Test,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Struct representing a java file
pub struct File {
/// path to java file.
path: PathBuf,
/// name of file.
file_name: String,
/// package the java file belongs to.
package_name: Option<String>,
/// imports made by the java file.
imports: Option<Vec<Dict>>,
/// name of the file TODO: How does this differ from `file_name`?
name: String,
/// colored terminal string representing java file name.
proper_name: String,
/// Name of tests methods in this file, as understood by JUnit.
test_methods: Vec<String>,
/// Name of tests methods in this file, colored using terminal color codes.
kind: FileType,
#[serde(skip)]
/// The parser for this file
parser: Parser,
/// Concise description of the file
description: String,
}
/// Two `File`s are equal if their paths are equal
impl PartialEq for File {
fn eq(&self, other: &Self) -> bool {
self.path == other.path
}
}
/// Based on PartialEq
impl Eq for File {}
/// Hash based on path
impl Hash for File {
fn hash<H: Hasher>(&self, state: &mut H) {
self.path.hash(state);
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
/// Struct representing a Java project.
/// Any index `i` in any collection in this struct always refers to the same
/// JavaFile.
pub struct Project {
/// Collection of java files in this project
files: Vec<File>,
/// Names of java files in this project.
names: Vec<String>,
/// Classpath
classpath: Vec<String>,
/// Source path
sourcepath: Vec<String>,
/// Root directory
root_dir: String,
}
#[derive(Clone)]
/// A struct that wraps a tree-sitter parser object and source code
pub struct Parser {
/// the source code being parsed
code: String,
/// the parse tree
_tree: Option<Tree>,
/// the tree-sitter java grammar language
lang: tree_sitter::Language,
}
impl Default for Parser {
fn default() -> Self {
let mut parser = tree_sitter::Parser::new();
let code = String::new();
parser
.set_language(*JAVA_TS_LANG)
.expect("Error loading Java grammar");
let tree = parser.parse(code, None);
Self {
code: String::new(),
_tree: tree,
lang: *JAVA_TS_LANG,
}
}
}
impl std::fmt::Debug for Parser {
fn fmt(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
Ok(())
}
}
impl Parser {
#[generate_rhai_variant(Impl, Fallible)]
/// Returns a new parser object
///
/// * `source_code`: the source code to be parsed
/// * `lang`: the tree-sitter grammar to use
pub fn new(source_code: String, lang: tree_sitter::Language) -> Result<Self> {
let mut parser = tree_sitter::Parser::new();
parser
.set_language(lang)
.expect("Error loading Java grammar");
let tree = parser
.parse(source_code.clone(), None)
.context("Error parsing Java code")?;
Ok(Self {
code: source_code,
_tree: Some(tree),
lang,
})
}
/// A getter for parser's source code
pub fn code(&mut self) -> String {
self.code.clone()
}
/// A setter for parser's source code
pub fn set_code(&mut self, code: String) {
self.code = code;
}
#[generate_rhai_variant(Fallible, Mut)]
/// Applies a tree sitter query and returns the result as a collection of
/// HashMaps
///
/// * `q`: the tree-sitter query to be applied
pub fn query(&self, q: &str) -> Result<Vec<Dict>> {
let mut results = vec![];
let tree = self
._tree
.as_ref()
.context("Treesitter could not parse code")?;
let query = Query::new(self.lang, q).unwrap();
let mut cursor = QueryCursor::new();
let matches = cursor.matches(&query, tree.root_node(), self.code.as_bytes());
let capture_names = query.capture_names();
for m in matches {
let mut result = Dict::new();
for name in capture_names {
let index = query.capture_index_for_name(name);
let index = match index {
Some(i) => i,
None => bail!(
"Error while querying source code. Capture name: {} has no index \
associated.",
name
),
};
let value = m.captures.iter().find(|c| c.index == index);
let value = match value {
Some(v) => v,
None => continue,
};
let value = value
.node
.utf8_text(self.code.as_bytes())
.with_context(|| {
format!(
"Cannot match query result indices with source code for capture name: \
{name}."
)
})?;
result.insert(name.clone(), value.to_string());
}
results.push(result);
}
Ok(results)
}
}
// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
impl CustomType for Parser {
fn build(mut builder: rhai::TypeBuilder<Self>) {
builder
.with_name("JavaParser")
.with_fn("new_java_parser", Parser::new_script)
.with_fn("code", Parser::code)
.with_fn("set_code", Parser::set_code)
.with_fn("query", Parser::query_mut_script);
}
}
/// An enum to represent possible errors with a Java file
#[derive(thiserror::Error, Debug)]
pub enum JavaFileError {
/// An error while compiling a Java file (running
/// [fn@crate::java::File::check])
#[error("Something went wrong while compiling the Java file")]
DuringCompilation {
/// javac stacktrace
stacktrace: String,
/// javac stacktrace, parsed with
/// [fn@crate::parsers::parser::parse_diag]
diags: Vec<JavacDiagnostic>,
},
/// An error while running a Java file (running
/// [fn@crate::java::File::run])
#[error("Something went wrong while running the Java file")]
AtRuntime {
/// java output
output: String,
/// java stacktrace, parsed with [parser::junit_stacktrace_line_ref]
diags: Vec<LineRef>,
},
/// An error while testing a Java file (running
/// [fn@crate::java::File::test])
#[error("Something went wrong while testing the Java file")]
FailedTests {
/// junit test results
test_results: String,
/// junit stacktrace, parsed with [parser::junit_stacktrace_line_ref]
diags: Vec<LineRef>,
},
/// Unknown error
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}
impl File {
#[generate_rhai_variant(Impl, Fallible)]
/// Creates a new `File` from `path`
///
/// * `path`: the path to read and try to create a File instance for.
fn new(path: PathBuf) -> Result<Self> {
let parser = {
let source_code = std::fs::read_to_string(&path)
.with_context(|| format!("Could not read file: {:?}", &path))?;
Parser::new(source_code, *JAVA_TS_LANG)?
};
let imports = {
let imports = parser.query(IMPORT_QUERY)?;
if imports.is_empty() {
None
} else {
Some(imports)
}
};
let package_name = {
let package_name = parser.query(PACKAGE_QUERY)?;
if package_name.is_empty() {
None
} else {
package_name[0].get("name").map(String::to_owned)
}
};
let (kind, name) = 'outer: {
let work = vec![
(FileType::Interface, INTERFACENAME_QUERY),
(FileType::ClassWithMain, CLASSNAME_QUERY),
(FileType::Class, CLASSNAME_QUERY),
];
for (kind, query) in work {
let result = parser.query(query)?;
if !result.is_empty() {
break 'outer (
kind,
#[allow(clippy::or_fun_call)]
result
.first()
.ok_or(anyhow!(
"Could not find a valid class/interface declaration for {} (vec \
size is 0)",
path.display()
))?
.get("name")
.ok_or(anyhow!(
"Could not find a valid class/interface declaration for {} \
(hashmap has no name key) ",
path.display()
))?
.to_string(),
);
}
}
(FileType::Class, String::new())
};
let proper_name = if package_name.is_some() {
format!("{}.{}", package_name.as_ref().unwrap(), name)
} else {
name.clone()
};
let test_methods = {
let test_methods = parser.query(TEST_ANNOTATION_QUERY)?;
let mut tests = vec![];
for t in test_methods {
if let Some(t) = t.get("name") {
tests.push(format!("{}#{}", &proper_name, t));
}
}
tests
};
let kind = if !test_methods.is_empty() {
FileType::Test
} else {
kind
};
let description = match kind {
FileType::Interface => {
let empty_dict = Dict::new();
let empty = String::new();
let not_found = String::from("[NOT FOUND]");
let query_result = parser
.query(INTERFACE_DECLARATION_QUERY)
.unwrap_or_default();
let declaration = query_result.first().unwrap_or(&empty_dict);
let parameters = declaration.get("parameters").unwrap_or(&empty).trim();
let extends = declaration.get("extends").unwrap_or(&empty).trim();
let consts = parser
.query(INTERFACE_CONSTANTS_QUERY)
.unwrap_or_default()
.iter()
.map(|c| c.get("constant").unwrap_or(¬_found).to_string())
.collect::<Vec<String>>()
.join("\n");
let methods = parser
.query(INTERFACE_METHODS_QUERY)
.unwrap_or_default()
.iter()
.map(|m| m.get("signature").unwrap_or(¬_found).to_string())
.collect::<Vec<String>>()
.join("\n");
let methods = if methods.trim().is_empty() {
String::from("[NOT FOUND]")
} else {
methods.trim().to_string()
};
let consts = if consts.trim().is_empty() {
String::from("[NOT FOUND]")
} else {
consts.trim().to_string()
};
let mut result = vec![];
result.push(format!(
"Interface: {proper_name} {parameters} {extends}:\n"
));
if !consts.contains("NOT FOUND") {
result.push(String::from("Constants:"));
result.push(consts);
}
if !methods.contains("NOT FOUND") {
result.push(String::from("Methods:"));
result.push(methods);
}
format!("```\n{r}\n```", r = result.join("\n"))
}
_ => {
let empty_dict = Dict::new();
let empty = String::new();
let not_found = String::from("[NOT FOUND]");
let query_result = parser.query(CLASS_DECLARATION_QUERY).unwrap_or_default();
let declaration = query_result.first().unwrap_or(&empty_dict);
let parameters = declaration.get("typeParameters").unwrap_or(&empty).trim();
let implements = declaration.get("interfaces").unwrap_or(&empty).trim();
let fields = parser
.query(CLASS_FIELDS_QUERY)
.unwrap_or_default()
.iter()
.map(|f| f.get("field").unwrap_or(¬_found).trim().to_string())
.collect::<Vec<String>>()
.join(", ");
let methods = parser
.query(CLASS_METHOD_QUERY)
.unwrap_or_default()
.iter()
.map(|m| {
let identifier = m.get("identifier").unwrap_or(¬_found).trim();
let parameters = m.get("parameters").unwrap_or(&empty);
if identifier == not_found.as_str() {
"[NOT FOUND]".to_string()
} else {
format!("{}{}", identifier.trim(), parameters.trim())
}
})
.collect::<Vec<String>>()
.join(", ");
let constructors = parser
.query(CLASS_CONSTRUCTOR_QUERY)
.unwrap_or_default()
.iter()
.map(|m| {
let identifier = m.get("identifier").unwrap_or(¬_found).trim();
let parameters = m.get("parameters").unwrap_or(&empty);
if identifier == not_found.as_str() {
"[NOT FOUND]".to_string()
} else {
format!("{}{}", identifier.trim(), parameters.trim())
}
})
.collect::<Vec<String>>()
.join(", ");
let fields = if fields.trim().is_empty() {
String::from("[NOT FOUND]")
} else {
format!("\tFields: {}", fields)
};
let methods = if methods.trim().is_empty() {
String::from("[NOT FOUND]")
} else {
format!("\tMethods: {}", methods)
};
let constructors = if constructors.trim().is_empty() {
String::from("[NOT FOUND]")
} else {
format!("\tConstructors: {}", constructors)
};
let mut result = vec![];
result.push(format!("Class: {proper_name} {parameters} {implements}:\n"));
if !fields.contains("NOT FOUND") {
result.push(fields);
}
if !constructors.contains("NOT FOUND") {
result.push(constructors);
}
if !methods.contains("NOT FOUND") {
result.push(methods);
}
result.join("\n")
}
};
Ok(Self {
path: path.to_owned(),
file_name: path.file_name().unwrap().to_str().unwrap().to_string(),
package_name,
imports,
name,
test_methods,
kind,
proper_name,
parser,
description,
})
}
/// Returns the inner doc check of this [`File`].
fn inner_doc_check(&self, err: Stdio, out: Stdio, in_: Stdio) -> Result<Output> {
Command::new(javac_path()?)
.stderr(err)
.stdout(out)
.stdin(in_)
.args([
"--source-path",
sourcepath()?.as_str(),
"-g",
"--class-path",
classpath()?.as_str(),
"-d",
BUILD_DIR.to_str().unwrap(),
self.path.as_path().to_str().unwrap(),
"-Xdiags:verbose",
"-Xdoclint",
// "-Xlint",
])
.output()
.context("Failed to spawn javac process.")
}
/// Utility method to ask javac for documentation lints using the -Xdoclint
/// flag.
///
/// The method simply returns the output produced by javac as a String.
/// There is a ['parse_diag method'][fn@crate::parsers::parser::parse_diag]
/// that can parse these to yield useful information.
pub fn doc_check(&self) -> Result<String, JavaFileError> {
let child = self.inner_doc_check(Stdio::piped(), Stdio::piped(), Stdio::piped())?;
let output = unescape(
&[
String::from_utf8(child.stderr).context("Error when parsing stderr as utf8")?,
String::from_utf8(child.stdout).context("Error when parsing stdout as utf8")?,
]
.concat(),
)
.context("Error when un-escaping javac output.")?;
Ok(output)
}
/// Utility method to ask javac for documentation lints using the -Xdoclint
/// flag.
///
/// The method simply returns the output produced by javac as a String.
/// There is a ['parse_diag method'][fn@crate::parsers::parser::parse_diag]
/// that can parse these to yield useful information.
pub fn doc_check_mut_script(&self) -> Result<String, Box<EvalAltResult>> {
match self.inner_doc_check(Stdio::inherit(), Stdio::inherit(), Stdio::inherit()) {
Ok(child) => match unescape(
&[
match String::from_utf8(child.stderr) {
Ok(s) => s,
Err(e) => {
return Err(format!("{}", e).into());
}
},
match String::from_utf8(child.stdout) {
Ok(s) => s,
Err(e) => {
return Err(format!("{}", e).into());
}
},
]
.concat(),
) {
Ok(s) => Ok(s),
Err(e) => Err(format!("{}", e).into()),
},
Err(e) => Err(Box::new(
unescape(e.to_string().as_str())
.unwrap_or_else(|_| format!("Could not unescape: {:?}", e))
.into(),
)),
}
}
/// Returns the inner check of this [`File`].
fn inner_check(&self, err: Stdio, out: Stdio, in_: Stdio) -> Result<Output> {
let path = self.path.display().to_string();
Command::new(javac_path()?)
.stderr(err)
.stdout(out)
.stdin(in_)
.args([
"--source-path",
sourcepath()?.as_str(),
"-g",
"--class-path",
classpath()?.as_str(),
"-d",
BUILD_DIR.to_str().unwrap(),
path.as_str(),
"-Xdiags:verbose",
// "-Xlint",
"-Xprefer:source",
])
.output()
.context("Failed to spawn javac process.")
}
/// Utility method to check for syntax errors using javac flag.
pub fn check(&self) -> Result<String, JavaFileError> {
match self.inner_check(Stdio::piped(), Stdio::piped(), Stdio::piped()) {
Ok(out) => {
let output = unescape(
&[
String::from_utf8(out.stderr).context("Error parsing stderr as utf8")?,
String::from_utf8(out.stdout).context("Error parsing stdout as utf8")?,
]
.concat(),
)
.context("Error when un-escaping javac output.")?;
if out.status.success() {
Ok(output)
} else {
let mut diags = Vec::new();
for line in output.lines() {
if let Ok(diag) = parser::parse_diag(line) {
diags.push(diag);
}
}
Err(JavaFileError::DuringCompilation {
stacktrace: output,
diags,
})
}
}
Err(e) => Err(JavaFileError::Unknown(e)),
}
}
/// Utility method to check for syntax errors using javac flag.
pub fn check_mut_script(&self) -> Result<String, Box<EvalAltResult>> {
match self.inner_check(Stdio::inherit(), Stdio::inherit(), Stdio::inherit()) {
Ok(child) => match unescape(
&[
match String::from_utf8(child.stderr) {
Ok(s) => s,
Err(e) => {
return Err(format!("{}", e).into());
}
},
match String::from_utf8(child.stdout) {
Ok(s) => s,
Err(e) => {
return Err(format!("{}", e).into());
}
},
]
.concat(),
) {
Ok(s) => Ok(s),
Err(e) => Err(format!("{}", e).into()),
},
Err(e) => Err(Box::new(
unescape(e.to_string().as_str())
.unwrap_or_else(|_| format!("Could not unescape: {:?}", e))
.into(),
)),
}
}
/// Returns the inner run of this [`File`].
fn inner_run(&self, input: Option<String>, err: Stdio, out: Stdio) -> Result<Output> {
if self.kind != FileType::ClassWithMain {
Err(JavaFileError::DuringCompilation {
stacktrace: "The file you wish to run does not have a main method.".into(),
diags: vec![],
})?;
}
if let Some(input_str) = input {
let mut child = Command::new(java_path()?)
.args([
"--class-path",
classpath()?.as_str(),
self.proper_name.clone().as_str(),
])
.stdin(Stdio::piped())
.stdout(out)
.stderr(err)
.spawn()
.context("Failed to spawn javac process.")?;
let input = format!("{}\r\n", input_str);
let mut stdin = child.stdin.take().unwrap();
stdin
.write_all(input.as_bytes())
.context("Error when trying to write input to stdin")?;
stdin.flush().context("Error when trying to flush stdin")?;
child
.wait_with_output()
.context("Error when waiting for child process to finish")
} else {
Command::new(java_path()?)
.args([
"--class-path",
classpath()?.as_str(),
self.proper_name.clone().as_str(),
])
.stdin(Stdio::inherit())
.stdout(out)
.stderr(err)
.spawn()?
.wait_with_output()
.context("Failed to spawn javac process.")
}
}
/// Utility method to run a java file that has a main method.
pub fn run(&self, input: Option<String>) -> Result<String, JavaFileError> {
self.check()?;
match self.inner_run(input, Stdio::piped(), Stdio::piped()) {
Ok(out) => {
let output = unescape(
&[
String::from_utf8(out.stderr)
.context("Error when parsing stderr as utf8")?,
String::from_utf8(out.stdout)
.context("Error when parsing stdout as utf8")?,
]
.concat(),
)
.context("Error when escaping java output.")?;
if out.status.success() {
Ok(output)
} else {
let mut diags = Vec::new();
for line in output.lines() {
if let Ok(diag) = parser::junit_stacktrace_line_ref(line) {
diags.push(diag);
}
}
Err(JavaFileError::AtRuntime {
output,
diags,
})
}
}
Err(e) => Err(anyhow!(e).into()),
}
}
/// Utility method to run a java file that has a main method.
pub fn run_mut_script(&self, input: Option<String>) -> Result<String, Box<EvalAltResult>> {
match self.inner_run(input, Stdio::inherit(), Stdio::inherit()) {
Ok(child) => match unescape(
&[
match String::from_utf8(child.stderr) {
Ok(s) => s,
Err(e) => {
return Err(format!("{}", e).into());
}
},
match String::from_utf8(child.stdout) {
Ok(s) => s,
Err(e) => {
return Err(format!("{}", e).into());
}
},
]
.concat(),
) {
Ok(s) => Ok(s),
Err(e) => Err(format!("{}", e).into()),
},
Err(e) => Err(Box::new(
unescape(e.to_string().as_str())
.unwrap_or_else(|_| format!("Could not unescape: {:?}", e))
.into(),
)),
}
}
/// Inner method to run tests.
fn inner_test(&self, tests: Vec<&str>, err: Stdio, out: Stdio, in_: Stdio) -> Result<Output> {
let tests = {
let mut new_tests = Vec::<String>::new();
for t in tests {
new_tests.push(format!("{}#{}", self.proper_name.clone(), t));
}
if new_tests.is_empty() {
self.test_methods.clone()
} else {
new_tests
}
};
let tests = tests
.iter()
.map(|s| format!("-m{s}"))
.collect::<Vec<String>>();
let methods: Vec<&str> = tests.iter().map(String::as_str).collect();
Command::new(java_path().context("Could not find `java` command on path.")?)
.stderr(err)
.stdout(out)
.stdin(in_)
.args(
[
[
"-jar",
LIB_DIR.join(JUNIT_PLATFORM).as_path().to_str().unwrap(),
"--disable-banner",
"--disable-ansi-colors",
"--details-theme=unicode",
"--single-color",
"-cp",
&classpath()?,
]
.as_slice(),
methods.as_slice(),
]
.concat(),
)
.output()
.context("Failed to spawn javac process.")
}
/// A utility method that takes a list of strings (or types that implement
/// `Into<String>`) meant to represent test method names, and runs those
/// tests.
///
/// Returns the output from JUnit as a string. There are parsers in
/// ['parsers module'][crate::parsers::parser] that helps parse this output.
///
/// * `tests`: list of strings (or types that implement
/// `Into<String>`) meant to represent test method names,
pub fn test(
&self,
tests: Vec<&str>,
project: Option<&Project>,
) -> Result<String, JavaFileError> {
self.check()?;
match self.inner_test(tests, Stdio::piped(), Stdio::piped(), Stdio::inherit()) {
Ok(out) => {
let output = unescape(
&[
String::from_utf8(out.stderr)
.context("Error when parsing stderr as utf8")?,
String::from_utf8(out.stdout)
.context("Error when parsing stdout as utf8")?,
]
.concat(),
)
.context("Error when un-escaping JUnit output.")?;
if out.status.success() {
Ok(output)
} else {
let mut diags = Vec::new();
let mut new_output = Vec::new();
for line in output.lines() {
if line.contains("MethodSource") || line.contains("Native Method") {
continue;
}
// if line.contains("Test run finished after") {
// break;
// }
if let Ok(diag) = parser::junit_stacktrace_line_ref(line) {
if let Some(proj) = project
&& proj.identify(diag.file_name()).is_ok()
{
new_output.push(
line.replace("\\\\", "\\").replace("\\\"", "\"").to_string(),
);
}
diags.push(diag);
} else if let Ok(diag) = parser::parse_diag(line) {
if let Some(proj) = project
&& proj.identify(diag.file_name()).is_ok()
{
new_output.push(
line.replace("\\\\", "\\").replace("\\\"", "\"").to_string(),
);
}
diags.push(diag.into());
} else {
new_output
.push(line.replace("\\\\", "\\").replace("\\\"", "\"").to_string());
}
}
Err(JavaFileError::FailedTests {
test_results: new_output.join("\n"),
diags,
})
}
}
Err(e) => Err(anyhow!(e).into()),
}
}
/// A utility method that takes a list of strings (or types that implement
/// `Into<String>`) meant to represent test method names, and runs those
/// tests.
pub fn test_mut_script(&mut self, tests: Vec<&str>) -> Result<String, Box<EvalAltResult>> {
match self.inner_test(tests, Stdio::inherit(), Stdio::inherit(), Stdio::inherit()) {
Ok(child) => match unescape(
&[
match String::from_utf8(child.stderr) {
Ok(s) => s,
Err(e) => {
return Err(format!("{}", e).into());
}
},
match String::from_utf8(child.stdout) {
Ok(s) => s,
Err(e) => {
return Err(format!("{}", e).into());
}
},
]
.concat(),
) {
Ok(s) => Ok(s),
Err(e) => Err(format!("{}", e).into()),
},
Err(e) => Err(Box::new(
unescape(e.to_string().as_str())
.unwrap_or_else(|_| format!("Could not unescape: {:?}", e))
.into(),
)),
}
}
/// A utility method that takes a list of strings (or types that implement
/// `Into<String>`) meant to represent test method names, and runs those
/// tests.
///
/// Returns the output from JUnit as a string. There are parsers in
/// ['parsers module'][crate::parsers::parser] that helps parse this output.
/// Get a reference to the file's kind.
pub fn kind(&self) -> &FileType {
&self.kind
}
/// Get a reference to the file's file name.
pub fn file_name(&self) -> &str {
self.file_name.as_ref()
}
/// Get a reference to the file's test methods.
pub fn test_methods(&self) -> Vec<String> {
self.test_methods.clone()
}
/// Get a reference to the file's test methods.
pub fn test_methods_mut_script(&mut self) -> Array {
self.test_methods().iter().map(|s| s.into()).collect()
}
/// treesitter query for this file
pub fn query(&self, q: &str) -> Result<Vec<Dict>> {
self.parser.query(q)
}
/// treesitter query for this file
pub fn query_mut_script(&mut self, q: &str) -> Result<Array, Box<EvalAltResult>> {
match self.parser.query(q) {
Ok(v) => {
let mut arr = Array::new();
for d in v {
arr.push(d.into());
}
Ok(arr)
}
Err(e) => Err(format!("Failed to query file: {e}").into()),
}
}
/// Get a reference to the file's path.
pub fn path(&self) -> &PathBuf {
&self.path
}
/// Get a reference to the file's path.
pub fn path_mut_script(&mut self) -> String {
self.path.display().to_string()
}
/// Get a reference to the file's proper name.
pub fn package_name(&self) -> Option<&String> {
self.package_name.as_ref()
}
/// Get a reference to the file's parser.
pub fn parser(&self) -> Parser {
self.parser.clone()
}
/// Get a reference to the file's description.
pub fn description(&self) -> String {
self.description.clone()
}
/// Get the file's proper name.
pub fn proper_name(&self) -> String {
self.proper_name.clone()
}
}
// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
impl CustomType for File {
fn build(mut builder: rhai::TypeBuilder<Self>) {
builder
.with_name("JavaFile")
.with_fn("new_java_file", File::new_script)
.with_fn("check", File::check_mut_script)
.with_fn("doc_check", File::doc_check_mut_script)
.with_fn("run", File::run_mut_script)
.with_fn("test", File::test_mut_script)
.with_fn("kind", File::kind)
.with_fn("file_name", File::file_name)
.with_fn("test_methods", File::test_methods_mut_script)
.with_fn("query", File::query_mut_script)
.with_fn("package_name", File::package_name)
.with_fn("path", File::path_mut_script)
.with_fn("parser", File::parser);
}
}
impl Project {
#[generate_rhai_variant(Impl, Fallible)]
/// Initializes a Project, by discovering java files in the
/// [struct@UMM_DIR] directory. Also downloads some `jar`
/// files required for unit testing and mutation testing.
pub fn new() -> Result<Self> {
let mut files = vec![];
let mut names = vec![];
let rt = RUNTIME.handle().clone();
let handles = FuturesUnordered::new();
let results = rt.block_on(async {
let found_files = match find_files("java", 15, &ROOT_DIR) {
Ok(f) => f,
Err(e) => panic!("Could not find java files: {e}"),
};
for path in found_files {
handles.push(rt.spawn_blocking(|| File::new(path)))
}
join_all(handles).await
});
for result in results {
let file = result??;
names.push(file.proper_name.clone());
files.push(file);
}
let classpath = vec![LIB_DIR.join("*.jar").display().to_string()];
let mut sourcepath = vec![
SOURCE_DIR.join("").display().to_string(),
TEST_DIR.join("").display().to_string(),
];
if !find_files("java", 0, &ROOT_DIR)?.is_empty() {
sourcepath.push(ROOT_DIR.join("").display().to_string());
}
let proj = Self {
files,
names,
classpath,
sourcepath,
root_dir: ROOT_DIR.display().to_string(),
};
let _guard = rt.enter();
rt.block_on(async {
let handles = FuturesUnordered::new();
let (proj1, proj2, proj3) = (proj.clone(), proj.clone(), proj.clone());
handles.push(tokio::spawn(async move {
proj1.download_libraries_if_needed().await
}));
handles.push(tokio::spawn(
async move { proj2.update_vscode_settings().await },
));
handles.push(tokio::spawn(
async move { proj3.update_vscode_tasks().await },
));
try_join_all(handles).await
})?
.into_iter()
.collect::<Result<Vec<()>>>()?;
Ok(proj)
}
#[generate_rhai_variant(Impl, Mut, Fallible)]
/// Attempts to identify the correct file from the project from a partial or
/// fully formed name as expected by a java compiler.
///
/// Returns a reference to the identified file, if any.
///
/// * `name`: partial/fully formed name of the Java file to look for.
pub fn identify(&self, name: &str) -> Result<File> {
let name: String = name.into();
if let Some(i) = self.names.iter().position(|n| *n == name) {
Ok(self.files[i].clone())
} else if let Some(i) = self.files.iter().position(|n| n.file_name == name) {
Ok(self.files[i].clone())
} else if let Some(i) = self
.files
.iter()
.position(|n| n.file_name.replace(".java", "") == name)
{
Ok(self.files[i].clone())
} else if let Some(i) = self.files.iter().position(|n| n.name.clone() == name) {
Ok(self.files[i].clone())
} else if let Some(i) = self
.files
.iter()
.position(|n| n.path.display().to_string() == name)
{
Ok(self.files[i].clone())
} else if let Some(i) = self.files.iter().position(|n| n.proper_name == name) {
Ok(self.files[i].clone())
} else {
bail!("Could not find {} in the project", name)
}
}
/// Returns true if project contains a file with the given name.
pub fn contains(&self, name: &str) -> bool {
self.identify(name).is_ok()
}
/// Downloads certain libraries like JUnit if found in imports.
/// times out after 20 seconds.
pub async fn download_libraries_if_needed(&self) -> Result<()> {
let need_junit = 'outer: {
for file in self.files.iter() {
if let Some(imports) = &file.imports {
for import in imports {
if let Some(path) = import.get(&String::from("path")) {
if path.starts_with("org.junit") {
break 'outer true;
}
}
}
}
}
false
};
if need_junit {
if !LIB_DIR.as_path().is_dir() {
std::fs::create_dir(LIB_DIR.as_path()).unwrap();
}
let handle1 = tokio::spawn(async {
download(
"https://ummfiles.fra1.digitaloceanspaces.com/jar_files/junit-platform-console-standalone-1.9.0-RC1.jar",
&LIB_DIR.join(JUNIT_PLATFORM),
false
)
.await
});
let handle2 = tokio::spawn(async {
download(
"https://ummfiles.fra1.digitaloceanspaces.com/jar_files/junit-4.13.2.jar",
&LIB_DIR.join("junit-4.13.2.jar"),
false,
)
.await
});
let handle3 = tokio::spawn(async {
download(
"https://ummfiles.fra1.digitaloceanspaces.com/jar_files/pitest-1.9.5.jar",
&LIB_DIR.join("pitest.jar"),
false,
)
.await
});
let handle4 = tokio::spawn(async {
download(
"https://ummfiles.fra1.digitaloceanspaces.com/jar_files/pitest-command-line-1.9.5.jar",
&LIB_DIR.join("pitest-command-line.jar"),
false,
)
.await
});
let handle5 = tokio::spawn(async {
download(
"https://ummfiles.fra1.digitaloceanspaces.com/jar_files/pitest-entry-1.9.5.jar",
&LIB_DIR.join("pitest-entry.jar"),
false,
)
.await
});
let handle6 = tokio::spawn(async {
download(
"https://ummfiles.fra1.digitaloceanspaces.com/jar_files/pitest-junit5-plugin-1.0.0.jar",
&LIB_DIR.join("pitest-junit5-plugin.jar"),
false,
)
.await
});
let handles =
FuturesUnordered::from_iter([handle1, handle2, handle3, handle4, handle5, handle6]);
futures::future::try_join_all(handles).await?;
}
Ok(())
}
/// Creates a vscode settings.json file for the project.
pub async fn update_vscode_settings(&self) -> Result<()> {
// TODO: Move this to an init function that takes CONSTANTS into account
if !ROOT_DIR.join(".vscode").as_path().is_dir() {
tokio::fs::create_dir(ROOT_DIR.join(".vscode").as_path())
.await
.unwrap();
}
if !ROOT_DIR.join(".vscode/settings.json").as_path().exists() {
let mut file = tokio::fs::OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(ROOT_DIR.join(".vscode").join("settings.json").as_path())
.await?;
let settings = vscode::SettingsFile::builder()
.java_source_path(self.sourcepath.clone())
.java_output_path(BUILD_DIR.join("").display().to_string())
.java_referenced_libs(self.classpath.clone())
.umm_binary_path(umm_path())
.build();
file.write_all(serde_json::to_string_pretty(&settings)?.as_bytes())
.await?;
}
// Do the same for extensions.json
if !ROOT_DIR.join(".vscode/extensions.json").as_path().exists() {
let mut file = tokio::fs::OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(ROOT_DIR.join(".vscode").join("extensions.json").as_path())
.await?;
let extensions = r#"
{
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"Codeium.codeium",
"vscjava.vscode-java-pack",
"ms-vsliveshare.vsliveshare"
],
// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
"unwantedRecommendations": [
]
}
"#;
file.write_all(extensions.as_bytes()).await?;
}
Ok(())
}
/// Get a reference to the project's files.
pub fn files(&self) -> &[File] {
self.files.as_ref()
}
#[generate_rhai_variant(Fallible)]
/// Prints project struct as a json
pub fn info(&self) -> Result<()> {
println!("{}", serde_json::to_string(&self)?);
Ok(())
}
/// Returns a short summary of the project, it's files, their fields and
/// methods.
pub fn describe(&self) -> String {
let mut result = String::new();
result.push_str(
"> What follows is a summary of the student's submission's files, their fields and \
methods generated via treesitter queries.\n\n",
);
for f in self.files.iter() {
if f.proper_name.contains("Hidden") {
continue;
}
result.push_str(f.description().as_str());
result.push_str("\n\n");
}
result
}
/// Writes a .vscode/tasks.json file for the project.
pub async fn update_vscode_tasks(&self) -> Result<()> {
let mut tasks = Vec::new();
let mut inputs = Vec::new();
let (default_depends_on, default_depends_order) = if umm_path() == "./umm" {
(
Some(vec!["Set umm to be executable".to_string()]),
Some(vscode::DependsOrder::Sequence),
)
} else {
(None, None)
};
tasks.push(
vscode::Task::builder()
.label("Set umm to be executable".to_string())
.r#type(vscode::Type::Shell)
.command("chmod")
.args(vec![
vscode::Args::builder()
.value("+x")
.quoting(vscode::ArgQuoting::Escape)
.build(),
vscode::Args::builder()
.value("${config:ummBinaryPath}")
.quoting(vscode::ArgQuoting::Weak)
.build(),
])
.depends_on(None)
.depends_order(None)
.build(),
);
tasks.push(
vscode::Task::builder()
.label("Clean library and target folders".to_string())
.r#type(vscode::Type::Shell)
.command("${config:ummBinaryPath}")
.args(vec![vscode::Args::builder()
.value("clean")
.quoting(vscode::ArgQuoting::Escape)
.build()])
.depends_on(default_depends_on.clone())
.depends_order(default_depends_order)
.build(),
);
tasks.push(
vscode::Task::builder()
.label("Reset project metadata".into())
.r#type(vscode::Type::Shell)
.command("${config:ummBinaryPath}")
.args(vec![vscode::Args::builder()
.value("reset")
.quoting(vscode::ArgQuoting::Escape)
.build()])
.depends_on(default_depends_on.clone())
.depends_order(default_depends_order)
.build(),
);
tasks.push(
vscode::Task::builder()
.label("Check health of the project".into())
.r#type(vscode::Type::Shell)
.command("${config:ummBinaryPath}")
.args(vec![vscode::Args::builder()
.value("check-health")
.quoting(vscode::ArgQuoting::Escape)
.build()])
.depends_on(default_depends_on.clone())
.depends_order(default_depends_order)
.build(),
);
tasks.push(
vscode::Task::builder()
.label("Update umm executable".into())
.r#type(vscode::Type::Shell)
.command("${config:ummBinaryPath}")
.args(vec![vscode::Args::builder()
.value("update")
.quoting(vscode::ArgQuoting::Escape)
.build()])
.depends_on(default_depends_on.clone())
.depends_order(default_depends_order)
.build(),
);
for file in self.files().iter() {
match file.kind() {
FileType::ClassWithMain => {
tasks.push(
vscode::Task::builder()
.label(format!("Run {}", file.name))
.r#type(vscode::Type::Shell)
.command("${config:ummBinaryPath}")
.args(vec![
vscode::Args::builder()
.value("run")
.quoting(vscode::ArgQuoting::Escape)
.build(),
vscode::Args::builder()
.value(&file.proper_name)
.quoting(vscode::ArgQuoting::Escape)
.build(),
])
.depends_on(default_depends_on.clone())
.depends_order(default_depends_order)
.build(),
);
}
FileType::Test => {
tasks.push(
vscode::Task::builder()
.label(format!("Run tests for {}", file.name))
.r#type(vscode::Type::Shell)
.command("${config:ummBinaryPath}")
.args(vec![
vscode::Args::builder()
.value("test")
.quoting(vscode::ArgQuoting::Escape)
.build(),
vscode::Args::builder()
.value(&file.proper_name)
.quoting(vscode::ArgQuoting::Escape)
.build(),
])
.group("test".to_string())
.depends_on(default_depends_on.clone())
.depends_order(default_depends_order)
.build(),
);
let mut test_methods = Vec::new();
for method in file.test_methods() {
let method = method.clone();
#[allow(clippy::or_fun_call)]
let method = method
.split_once('#')
.ok_or(anyhow!("Could not parse test method - {}", method))?
.1;
// commands.push(method.into());
test_methods.push(String::from(method));
}
if !test_methods.is_empty() {
let input = vscode::Input::PickString {
id: file.proper_name.to_string(),
description: "Which test to run?".to_string(),
options: test_methods.clone(),
default: test_methods.first().unwrap().clone(),
};
inputs.push(input);
}
tasks.push(
vscode::Task::builder()
.label(format!("Run specific test from {}", file.name))
.r#type(vscode::Type::Shell)
.command("${config:ummBinaryPath}")
.args(vec![
vscode::Args::builder()
.value("test")
.quoting(vscode::ArgQuoting::Escape)
.build(),
vscode::Args::builder()
.value(&file.proper_name)
.quoting(vscode::ArgQuoting::Escape)
.build(),
vscode::Args::builder()
.value(format!("${{input:{}}}", file.proper_name))
.quoting(vscode::ArgQuoting::Escape)
.build(),
])
.group("test".to_string())
.depends_on(default_depends_on.clone())
.depends_order(default_depends_order)
.build(),
);
}
_ => {}
};
tasks.push(
vscode::Task::builder()
.label(format!("Check {}", file.name))
.r#type(vscode::Type::Shell)
.command("${config:ummBinaryPath}")
.args(vec![
vscode::Args::builder()
.value("check")
.quoting(vscode::ArgQuoting::Escape)
.build(),
vscode::Args::builder()
.value(&file.proper_name)
.quoting(vscode::ArgQuoting::Escape)
.build(),
])
.depends_on(default_depends_on.clone())
.depends_order(default_depends_order)
.build(),
);
tasks.push(
vscode::Task::builder()
.label(format!("Check JavaDoc for {}", file.name))
.r#type(vscode::Type::Shell)
.command("${config:ummBinaryPath}")
.args(vec![
vscode::Args::builder()
.value("doc-check")
.quoting(vscode::ArgQuoting::Escape)
.build(),
vscode::Args::builder()
.value(&file.proper_name)
.quoting(vscode::ArgQuoting::Escape)
.build(),
])
.depends_on(default_depends_on.clone())
.depends_order(default_depends_order)
.build(),
);
}
let rhai_scripts = {
let scripts = find_files(".rhai", 3, &ROOT_DIR)?
.iter()
.map(|f| f.display().to_string())
.collect::<Vec<String>>();
if scripts.is_empty() {
vec!["script.rhai".to_string()]
} else {
scripts
}
};
inputs.push(vscode::Input::PickString {
id: "gradable_assignments".to_string(),
description: "What script to use?".to_string(),
options: rhai_scripts.clone(),
default: rhai_scripts.first().unwrap().clone(),
});
tasks.push(
vscode::Task::builder()
.label("Grade Assignment".to_string())
.r#type(vscode::Type::Shell)
.command("${config:ummBinaryPath}")
.args(vec![
vscode::Args::builder()
.value("grade")
.quoting(vscode::ArgQuoting::Escape)
.build(),
vscode::Args::builder()
.value("${input:gradable_assignments}".to_string())
.quoting(vscode::ArgQuoting::Escape)
.build(),
])
.problem_matcher(Some(vec![vscode::ProblemMatcher::builder()
.apply_to("allDocuments".to_string())
.file_location(vec![
"relative".to_string(),
"${workspaceFolder}".to_string(),
])
.owner("umm".to_string())
.pattern(
vscode::Pattern::builder()
.regexp(r#"\s*[│]\s*([\w./]+)\s*[│]\s*([0-9]+)\s*[│]\s*([\w ]+)"#)
.file(1)
.line(2)
.end_line(2)
.message(3)
.build(),
)
.build()]))
.depends_on(default_depends_on)
.depends_order(default_depends_order)
.build(),
);
if !ROOT_DIR.join(".vscode").as_path().exists() {
tokio::fs::create_dir(ROOT_DIR.join(".vscode").as_path())
.await
.unwrap();
}
let mut file = tokio::fs::OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(ROOT_DIR.join(".vscode").join("tasks.json").as_path())
.await?;
let task_file = vscode::TasksFile::builder()
.tasks(tasks)
.inputs(inputs)
.build();
file.write_all(serde_json::to_string_pretty(&task_file)?.as_bytes())
.await?;
Ok(())
}
/// Serves the project code as a static website.
pub fn serve_project_code(&self) -> anyhow::Result<()> {
let mut markdown = format!(
"# Student Submission Source Code\n\n## Overview\n\n{}\n\n## Source Code\n\n",
self.describe()
);
for file in &self.files {
markdown.push_str(&format!(
"### {}\n\n```java\n{}\n```\n\n",
file.proper_name(),
file.parser().code()
));
}
let id = uuid::Uuid::new_v4().to_string();
let submission = serde_json::to_string(&SubmissionRow {
id: id.clone(),
course: COURSE.to_string(),
term: TERM.to_string(),
content: markdown,
})?;
let rt = RUNTIME.handle().clone();
rt.block_on(async {
POSTGREST_CLIENT
.from("submissions")
.insert(submission)
.execute()
.await
})?;
println!(
"Please visit https://feedback.dhruvdh.com/submissions/{} to see your submission code.",
id
);
Ok(())
}
}
/// Schema for `submissions` table
#[derive(Serialize, Debug)]
pub struct SubmissionRow {
/// UUID of data entry
id: String,
/// Course the submission belongs to
course: String,
/// Term of the course
term: String,
/// Content of the submission
content: String,
}
// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
impl CustomType for Project {
fn build(mut builder: rhai::TypeBuilder<Self>) {
builder
.with_name("JavaProject")
.with_fn("new_java_project", Project::new_script)
.with_fn("identify", Project::identify_mut_script)
.with_fn("files", Project::files)
.with_fn("info", Project::info_script);
}
}