-
-
Notifications
You must be signed in to change notification settings - Fork 716
Expand file tree
/
Copy pathoptions.rs
More file actions
227 lines (188 loc) · 4.68 KB
/
options.rs
File metadata and controls
227 lines (188 loc) · 4.68 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
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
use crate::args::get_app_config_path;
use anyhow::Result;
use asyncgit::sync::{
diff::DiffOptions, repo_dir, RepoPathRef,
ShowUntrackedFilesConfig,
};
use ron::{
de::from_bytes,
ser::{to_string_pretty, PrettyConfig},
};
use serde::{Deserialize, Serialize};
use std::{
cell::RefCell,
fs::File,
io::{Read, Write},
path::PathBuf,
rc::Rc,
};
#[derive(Default, Clone, Serialize, Deserialize)]
#[serde(default)]
struct OptionsData {
pub tab: usize,
pub diff: DiffOptions,
pub status_show_untracked: Option<ShowUntrackedFilesConfig>,
pub commit_msgs: Vec<String>,
}
const COMMIT_MSG_HISTORY_LENGTH: usize = 20;
const OPTIONS_FILENAME: &str = "gitui.ron";
#[derive(Clone)]
pub struct Options {
repo: RepoPathRef,
data: OptionsData,
}
#[cfg(test)]
impl Options {
pub fn test_env() -> Self {
use asyncgit::sync::RepoPath;
Self {
repo: RefCell::new(RepoPath::Path(Default::default())),
data: Default::default(),
}
}
}
pub type SharedOptions = Rc<RefCell<Options>>;
impl Options {
pub fn new(repo: RepoPathRef) -> SharedOptions {
Rc::new(RefCell::new(Self {
data: Self::read(&repo).unwrap_or_default(),
repo,
}))
}
pub fn set_current_tab(&mut self, tab: usize) {
self.data.tab = tab;
self.save();
}
pub const fn current_tab(&self) -> usize {
self.data.tab
}
pub const fn diff_options(&self) -> DiffOptions {
self.data.diff
}
pub const fn status_show_untracked(
&self,
) -> Option<ShowUntrackedFilesConfig> {
self.data.status_show_untracked
}
pub fn set_status_show_untracked(
&mut self,
value: Option<ShowUntrackedFilesConfig>,
) {
self.data.status_show_untracked = value;
self.save();
}
pub fn diff_context_change(&mut self, increase: bool) {
self.data.diff.context = if increase {
self.data.diff.context.saturating_add(1)
} else {
self.data.diff.context.saturating_sub(1)
};
self.save();
}
pub fn diff_hunk_lines_change(&mut self, increase: bool) {
self.data.diff.interhunk_lines = if increase {
self.data.diff.interhunk_lines.saturating_add(1)
} else {
self.data.diff.interhunk_lines.saturating_sub(1)
};
self.save();
}
pub fn diff_toggle_whitespace(&mut self) {
self.data.diff.ignore_whitespace =
!self.data.diff.ignore_whitespace;
self.save();
}
pub fn add_commit_msg(&mut self, msg: &str) {
self.data.commit_msgs.push(msg.to_owned());
while self.data.commit_msgs.len() > COMMIT_MSG_HISTORY_LENGTH
{
self.data.commit_msgs.remove(0);
}
self.save();
}
pub fn has_commit_msg_history(&self) -> bool {
!self.data.commit_msgs.is_empty()
}
pub fn commit_msg(&self, idx: usize) -> Option<String> {
if self.data.commit_msgs.is_empty() {
None
} else {
let entries = self.data.commit_msgs.len();
let mut index = idx;
while index >= entries {
index -= entries;
}
index = entries.saturating_sub(1) - index;
Some(self.data.commit_msgs[index].clone())
}
}
fn save(&self) {
if let Err(e) = self.save_failable() {
log::error!("options save error: {e}");
}
}
fn read(repo: &RepoPathRef) -> Result<OptionsData> {
let local_file = Self::options_file(repo)?;
// Precedence: local -> global (respects GITUI_CONFIG_DIR)
let mut f = match File::open(&local_file) {
Ok(file) => file,
Err(_) => {
let app_home = get_app_config_path()?;
let global_file = app_home.join(OPTIONS_FILENAME);
File::open(global_file)?
}
};
let mut buffer = Vec::new();
f.read_to_end(&mut buffer)?;
Ok(from_bytes(&buffer)?)
}
fn save_failable(&self) -> Result<()> {
let dir = Self::options_file(&self.repo)?;
let mut file = File::create(dir)?;
let data =
to_string_pretty(&self.data, PrettyConfig::default())?;
file.write_all(data.as_bytes())?;
Ok(())
}
fn options_file(repo: &RepoPathRef) -> Result<PathBuf> {
let dir = repo_dir(&repo.borrow())?;
let dir = dir.join(OPTIONS_FILENAME);
Ok(dir)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{env, fs};
#[test]
fn read_falls_back_to_global_config() {
let global_dir = tempfile::tempdir().unwrap();
let global_file =
global_dir.path().join(OPTIONS_FILENAME);
fs::write(
&global_file,
"(diff: (ignore_whitespace: true))",
)
.unwrap();
env::set_var(
"GITUI_CONFIG_DIR",
global_dir.path().to_str().unwrap(),
);
// Init a real git repo so repo_dir() works
let repo_dir = tempfile::tempdir().unwrap();
std::process::Command::new("git")
.args(["init"])
.current_dir(repo_dir.path())
.output()
.unwrap();
let git_dir = repo_dir.path().join(".git");
let repo = RefCell::new(
asyncgit::sync::RepoPath::Path(
git_dir.to_path_buf(),
),
);
let data = Options::read(&repo).unwrap();
assert!(data.diff.ignore_whitespace);
env::remove_var("GITUI_CONFIG_DIR");
}
}