-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathworkspace_file.rs
More file actions
79 lines (69 loc) · 2.55 KB
/
workspace_file.rs
File metadata and controls
79 lines (69 loc) · 2.55 KB
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
use crate::execute::diagnostics::{ResultExt, ResultIoExt};
use crate::execute::process_file::SharedTraversalOptions;
use pglt_diagnostics::{Error, category};
use pglt_fs::{File, OpenOptions, PgLTPath};
use pglt_workspace::workspace::{ChangeParams, FileGuard, OpenFileParams};
use pglt_workspace::{Workspace, WorkspaceError};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
/// Small wrapper that holds information and operations around the current processed file
pub(crate) struct WorkspaceFile<'ctx, 'app> {
guard: FileGuard<'app, dyn Workspace + 'ctx>,
file: Box<dyn File>,
pub(crate) path: PathBuf,
}
impl<'ctx, 'app> WorkspaceFile<'ctx, 'app> {
/// It attempts to read the file from disk, creating a [FileGuard] and
/// saving these information internally
pub(crate) fn new(
ctx: &SharedTraversalOptions<'ctx, 'app>,
path: &Path,
) -> Result<Self, Error> {
let pglt_path = PgLTPath::new(path);
let open_options = OpenOptions::default()
.read(true)
.write(ctx.execution.requires_write_access());
let mut file = ctx
.fs
.open_with_options(path, open_options)
.with_file_path(path.display().to_string())?;
let mut input = String::new();
file.read_to_string(&mut input)
.with_file_path(path.display().to_string())?;
let guard = FileGuard::open(
ctx.workspace,
OpenFileParams {
path: pglt_path,
version: 0,
content: input.clone(),
},
)
.with_file_path_and_code(path.display().to_string(), category!("internalError/fs"))?;
Ok(Self {
file,
guard,
path: PathBuf::from(path),
})
}
pub(crate) fn guard(&self) -> &FileGuard<'app, dyn Workspace + 'ctx> {
&self.guard
}
pub(crate) fn input(&self) -> Result<String, WorkspaceError> {
self.guard().get_file_content()
}
pub(crate) fn as_extension(&self) -> Option<&OsStr> {
self.path.extension()
}
/// It updates the workspace file with `new_content`
pub(crate) fn update_file(&mut self, new_content: impl Into<String>) -> Result<(), Error> {
let new_content = new_content.into();
self.file
.set_content(new_content.as_bytes())
.with_file_path(self.path.display().to_string())?;
self.guard.change_file(
self.file.file_version(),
vec![ChangeParams::overwrite(new_content)],
)?;
Ok(())
}
}