Skip to content

Commit ebab8c8

Browse files
committed
formatting and adding a buncha log points
1 parent 7cf009e commit ebab8c8

File tree

9 files changed

+711
-860
lines changed

9 files changed

+711
-860
lines changed

server/src/commands.rs

Lines changed: 37 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,37 @@
1-
use std::{collections::HashMap, path::{Path, PathBuf}};
2-
use std::rc::Rc;
31
use std::cell::RefCell;
42
use std::fs::OpenOptions;
53
use std::io::prelude::*;
4+
use std::rc::Rc;
5+
use std::{
6+
collections::HashMap,
7+
path::{Path, PathBuf},
8+
};
69

10+
use petgraph::dot::Config;
711
use serde_json::Value;
812

913
use petgraph::{dot, graph::NodeIndex};
1014

11-
use anyhow::{Result, format_err};
15+
use anyhow::{format_err, Result};
16+
use slog_scope::info;
1217

1318
use std::fs;
1419

15-
use crate::{graph::CachedStableGraph, merge_views, url_norm::FromJson};
1620
use crate::dfs;
21+
use crate::{graph::CachedStableGraph, merge_views, url_norm::FromJson};
1722

1823
pub struct CustomCommandProvider {
19-
commands: HashMap<String, Box<dyn Invokeable>>
24+
commands: HashMap<String, Box<dyn Invokeable>>,
2025
}
2126

2227
impl CustomCommandProvider {
2328
pub fn new(commands: Vec<(&str, Box<dyn Invokeable>)>) -> CustomCommandProvider {
24-
CustomCommandProvider{
25-
commands: commands.into_iter().map(|tup| {
26-
(tup.0.into(), tup.1)
27-
}).collect(),
29+
CustomCommandProvider {
30+
commands: commands.into_iter().map(|tup| (tup.0.into(), tup.1)).collect(),
2831
}
2932
}
3033

31-
pub fn execute(&self, command: &str, args: Vec<Value>, root_path: &Path) -> Result<Value> {
34+
pub fn execute(&self, command: &str, args: &[Value], root_path: &Path) -> Result<Value> {
3235
if self.commands.contains_key(command) {
3336
return self.commands.get(command).unwrap().run_command(root_path, args);
3437
}
@@ -37,43 +40,42 @@ impl CustomCommandProvider {
3740
}
3841

3942
pub trait Invokeable {
40-
fn run_command(&self, root: &Path, arguments: Vec<Value>) -> Result<Value>;
43+
fn run_command(&self, root: &Path, arguments: &[Value]) -> Result<Value>;
4144
}
4245

4346
pub struct GraphDotCommand {
44-
pub graph: Rc<RefCell<CachedStableGraph>>
47+
pub graph: Rc<RefCell<CachedStableGraph>>,
4548
}
4649

4750
impl Invokeable for GraphDotCommand {
48-
fn run_command(&self, root: &Path, _: Vec<Value>) -> Result<Value> {
51+
fn run_command(&self, root: &Path, _: &[Value]) -> Result<Value> {
4952
let filepath = root.join("graph.dot");
50-
eprintln!("generating dot file at {:?}", filepath);
51-
let mut file = OpenOptions::new()
52-
.truncate(true)
53-
.write(true)
54-
.create(true)
55-
.open(filepath)
56-
.unwrap();
53+
54+
info!("generating dot file"; "path" => filepath.as_os_str().to_str());
55+
56+
let mut file = OpenOptions::new().truncate(true).write(true).create(true).open(filepath).unwrap();
5757

5858
let mut write_data_closure = || -> Result<(), std::io::Error> {
5959
let graph = self.graph.as_ref();
6060

6161
file.seek(std::io::SeekFrom::Start(0))?;
62-
file.write_all(dot::Dot::new(&graph.borrow().graph).to_string().as_bytes())?;
62+
file.write_all("digraph {\n\tgraph [splines=ortho]\n\tnode [shape=box]\n".as_bytes())?;
63+
file.write_all(dot::Dot::with_config(&graph.borrow().graph, &[Config::GraphContentOnly]).to_string().as_bytes())?;
64+
file.write_all("\n}".as_bytes())?;
6365
file.flush()?;
6466
file.seek(std::io::SeekFrom::Start(0))?;
6567
Ok(())
6668
};
6769

6870
match write_data_closure() {
69-
Err(err) => Err(format_err!("Error generating graphviz data: {}", err)),
70-
_ => Ok(Value::Null)
71+
Err(err) => Err(format_err!("error generating graphviz data: {}", err)),
72+
_ => Ok(Value::Null),
7173
}
7274
}
7375
}
7476

7577
pub struct VirtualMergedDocument {
76-
pub graph: Rc<RefCell<CachedStableGraph>>
78+
pub graph: Rc<RefCell<CachedStableGraph>>,
7779
}
7880

7981
impl VirtualMergedDocument {
@@ -111,7 +113,7 @@ impl VirtualMergedDocument {
111113

112114
let source = match fs::read_to_string(&path) {
113115
Ok(s) => s,
114-
Err(e) => return Err(format_err!("error reading {:?}: {}", path, e))
116+
Err(e) => return Err(format_err!("error reading {:?}: {}", path, e)),
115117
};
116118
let source = source.replace("\r\n", "\n");
117119
sources.insert(path.clone(), source);
@@ -122,7 +124,7 @@ impl VirtualMergedDocument {
122124
}
123125

124126
impl Invokeable for VirtualMergedDocument {
125-
fn run_command(&self, root: &Path, arguments: Vec<Value>) -> Result<Value> {
127+
fn run_command(&self, root: &Path, arguments: &[Value]) -> Result<Value> {
126128
let path = PathBuf::from_json(arguments.get(0).unwrap())?;
127129

128130
let file_ancestors = match self.get_file_toplevel_ancestors(&path) {
@@ -132,15 +134,15 @@ impl Invokeable for VirtualMergedDocument {
132134
},
133135
Err(e) => return Err(e),
134136
};
135-
136-
//eprintln!("ancestors for {}:\n\t{:?}", path, file_ancestors.iter().map(|e| self.graph.borrow().graph.node_weight(*e).unwrap().clone()).collect::<Vec<String>>());
137+
138+
//info!("ancestors for {}:\n\t{:?}", path, file_ancestors.iter().map(|e| self.graph.borrow().graph.node_weight(*e).unwrap().clone()).collect::<Vec<String>>());
137139

138140
// the set of all filepath->content. TODO: change to Url?
139141
let mut all_sources: HashMap<PathBuf, String> = HashMap::new();
140142

141143
// if we are a top-level file (this has to be one of the set defined by Optifine, right?)
142144
if file_ancestors.is_empty() {
143-
// gather the list of all descendants
145+
// gather the list of all descendants
144146
let root = self.graph.borrow_mut().find_node(&path).unwrap();
145147
let tree = match self.get_dfs_for_node(root) {
146148
Ok(tree) => tree,
@@ -149,14 +151,17 @@ impl Invokeable for VirtualMergedDocument {
149151

150152
let sources = match self.load_sources(&tree) {
151153
Ok(s) => s,
152-
Err(e) => return Err(e)
154+
Err(e) => return Err(e),
153155
};
154156
all_sources.extend(sources);
155157

156158
let graph = self.graph.borrow();
157159
let view = merge_views::generate_merge_list(&tree, &all_sources, &graph);
158160
return Ok(serde_json::value::Value::String(view));
159161
}
160-
return Err(format_err!("{:?} is not a top-level file aka has ancestors", path.strip_prefix(root).unwrap()))
162+
return Err(format_err!(
163+
"{:?} is not a top-level file aka has ancestors",
164+
path.strip_prefix(root).unwrap()
165+
));
161166
}
162-
}
167+
}

server/src/dfs.rs

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,19 @@ struct VisitCount {
1010
children: usize,
1111
}
1212

13-
/// Performs a depth-first search with duplicates
13+
/// Performs a depth-first search with duplicates
1414
pub struct Dfs<'a> {
1515
stack: Vec<NodeIndex>,
1616
graph: &'a CachedStableGraph,
17-
cycle: Vec<VisitCount>
17+
cycle: Vec<VisitCount>,
1818
}
1919

20-
impl <'a> Dfs<'a> {
20+
impl<'a> Dfs<'a> {
2121
pub fn new(graph: &'a CachedStableGraph, start: NodeIndex) -> Self {
2222
Dfs {
2323
stack: vec![start],
2424
graph,
25-
cycle: Vec::new()
25+
cycle: Vec::new(),
2626
}
2727
}
2828

@@ -42,49 +42,44 @@ impl <'a> Dfs<'a> {
4242
for child in children {
4343
if prev.node == *child {
4444
let cycle_nodes: Vec<NodeIndex> = self.cycle.iter().map(|n| n.node).collect();
45-
return Err(
46-
error::CycleError::new(&cycle_nodes, *child, self.graph)
47-
);
45+
return Err(error::CycleError::new(&cycle_nodes, *child, self.graph));
4846
}
4947
}
5048
}
5149
Ok(())
52-
}
50+
}
5351
}
5452

55-
impl <'a> Iterator for Dfs<'a> {
53+
impl<'a> Iterator for Dfs<'a> {
5654
type Item = Result<(NodeIndex, Option<NodeIndex>), error::CycleError>;
5755

5856
fn next(&mut self) -> Option<Result<(NodeIndex, Option<NodeIndex>), error::CycleError>> {
59-
let parent = match self.cycle.last() {
60-
Some(p) => Some(p.node),
61-
None => None,
62-
};
57+
let parent = self.cycle.last().map(|p| p.node);
6358

6459
if let Some(node) = self.stack.pop() {
65-
self.cycle.push(VisitCount{
60+
self.cycle.push(VisitCount {
6661
node,
6762
children: self.graph.graph.edges(node).count(),
6863
touch: 1,
6964
});
7065

7166
let mut children = self.graph.child_node_indexes(node);
72-
67+
7368
if !children.is_empty() {
7469
// sort by line number in parent
7570
children.sort_by(|x, y| {
7671
let graph = &self.graph.graph;
7772
let edge1 = graph.edge_weight(graph.find_edge(node, *x).unwrap()).unwrap();
7873
let edge2 = graph.edge_weight(graph.find_edge(node, *y).unwrap()).unwrap();
79-
74+
8075
edge2.line.cmp(&edge1.line)
8176
});
82-
77+
8378
match self.check_for_cycle(&children) {
8479
Ok(_) => {}
8580
Err(e) => return Some(Err(e)),
8681
};
87-
82+
8883
for child in children {
8984
self.stack.push(child);
9085
}
@@ -101,40 +96,44 @@ impl <'a> Iterator for Dfs<'a> {
10196
pub mod error {
10297
use petgraph::stable_graph::NodeIndex;
10398

104-
use std::{fmt::{Debug, Display}, path::PathBuf, error::Error as StdError};
99+
use std::{
100+
error::Error as StdError,
101+
fmt::{Debug, Display},
102+
path::PathBuf,
103+
};
105104

106-
use crate::{graph::CachedStableGraph, consts};
105+
use crate::{consts, graph::CachedStableGraph};
107106

108107
use rust_lsp::lsp_types::{Diagnostic, DiagnosticSeverity, Position, Range};
109108

110109
#[derive(Debug)]
111110
pub struct CycleError(Vec<PathBuf>);
112111

113112
impl StdError for CycleError {}
114-
113+
115114
impl CycleError {
116115
pub fn new(nodes: &[NodeIndex], current_node: NodeIndex, graph: &CachedStableGraph) -> Self {
117116
let mut resolved_nodes: Vec<PathBuf> = nodes.iter().map(|i| graph.get_node(*i)).collect();
118117
resolved_nodes.push(graph.get_node(current_node));
119118
CycleError(resolved_nodes)
120119
}
121120
}
122-
121+
123122
impl Display for CycleError {
124123
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125124
let mut disp = String::new();
126125
disp.push_str(format!("Include cycle detected:\n{:?} imports ", self.0[0]).as_str());
127-
for p in &self.0[1..self.0.len()-1] {
126+
for p in &self.0[1..self.0.len() - 1] {
128127
disp.push_str(format!("\n{:?}, which imports ", *p).as_str());
129128
}
130-
disp.push_str(format!("\n{:?}", self.0[self.0.len()-1]).as_str());
129+
disp.push_str(format!("\n{:?}", self.0[self.0.len() - 1]).as_str());
131130
f.write_str(disp.as_str())
132131
}
133132
}
134133

135134
impl From<CycleError> for Diagnostic {
136135
fn from(e: CycleError) -> Diagnostic {
137-
Diagnostic{
136+
Diagnostic {
138137
severity: Some(DiagnosticSeverity::Error),
139138
range: Range::new(Position::new(0, 0), Position::new(0, 500)),
140139
source: Some(consts::SOURCE.into()),
@@ -153,4 +152,4 @@ pub mod error {
153152
format!("{}", e)
154153
}
155154
}
156-
}
155+
}

server/src/graph.rs

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1-
use petgraph::stable_graph::StableDiGraph;
1+
use petgraph::stable_graph::EdgeIndex;
22
use petgraph::stable_graph::NodeIndex;
3+
use petgraph::stable_graph::StableDiGraph;
34
use petgraph::Direction;
4-
use petgraph::stable_graph::EdgeIndex;
55

6-
use std::{collections::{HashMap, HashSet}, path::{Path, PathBuf}, str::FromStr};
6+
use std::{
7+
collections::{HashMap, HashSet},
8+
path::{Path, PathBuf},
9+
str::FromStr,
10+
};
711

812
use super::IncludePosition;
913

@@ -16,14 +20,14 @@ pub struct CachedStableGraph {
1620
pub graph: StableDiGraph<String, IncludePosition>,
1721
cache: HashMap<PathBuf, NodeIndex>,
1822
// Maps a node index to its abstracted string representation.
19-
// Mainly used as the graph is based on NodeIndex and
23+
// Mainly used as the graph is based on NodeIndex.
2024
reverse_index: HashMap<NodeIndex, PathBuf>,
2125
}
2226

2327
impl CachedStableGraph {
2428
#[allow(clippy::new_without_default)]
2529
pub fn new() -> CachedStableGraph {
26-
CachedStableGraph{
30+
CachedStableGraph {
2731
graph: StableDiGraph::new(),
2832
cache: HashMap::new(),
2933
reverse_index: HashMap::new(),
@@ -91,15 +95,21 @@ impl CachedStableGraph {
9195

9296
#[allow(dead_code)]
9397
pub fn child_node_names(&self, node: NodeIndex) -> Vec<PathBuf> {
94-
self.graph.neighbors(node).map(|n| self.reverse_index.get(&n).unwrap().clone()).collect()
98+
self.graph
99+
.neighbors(node)
100+
.map(|n| self.reverse_index.get(&n).unwrap().clone())
101+
.collect()
95102
}
96103

97104
pub fn child_node_meta(&self, node: NodeIndex) -> Vec<(PathBuf, IncludePosition)> {
98-
self.graph.neighbors(node).map(|n| {
99-
let edge = self.graph.find_edge(node, n).unwrap();
100-
let edge_meta = self.graph.edge_weight(edge).unwrap();
101-
return (self.reverse_index.get(&n).unwrap().clone(), edge_meta.clone())
102-
}).collect()
105+
self.graph
106+
.neighbors(node)
107+
.map(|n| {
108+
let edge = self.graph.find_edge(node, n).unwrap();
109+
let edge_meta = self.graph.edge_weight(edge).unwrap();
110+
return (self.reverse_index.get(&n).unwrap().clone(), edge_meta.clone());
111+
})
112+
.collect()
103113
}
104114

105115
pub fn child_node_indexes(&self, node: NodeIndex) -> Vec<NodeIndex> {
@@ -108,7 +118,10 @@ impl CachedStableGraph {
108118

109119
#[allow(dead_code)]
110120
pub fn parent_node_names(&self, node: NodeIndex) -> Vec<PathBuf> {
111-
self.graph.neighbors_directed(node, Direction::Incoming).map(|n| self.reverse_index.get(&n).unwrap().clone()).collect()
121+
self.graph
122+
.neighbors_directed(node, Direction::Incoming)
123+
.map(|n| self.reverse_index.get(&n).unwrap().clone())
124+
.collect()
112125
}
113126

114127
pub fn parent_node_indexes(&self, node: NodeIndex) -> Vec<NodeIndex> {
@@ -129,7 +142,7 @@ impl CachedStableGraph {
129142
if node == initial && !visited.is_empty() {
130143
return vec![];
131144
}
132-
145+
133146
let parents = self.parent_node_indexes(node);
134147
let mut collection = Vec::with_capacity(parents.len());
135148

@@ -148,4 +161,4 @@ impl CachedStableGraph {
148161

149162
collection
150163
}
151-
}
164+
}

0 commit comments

Comments
 (0)