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
use std::path::PathBuf;
use git_features::threading::OwnShared;
use git_sec::Trust;
use crate::{Permissions, ThreadSafeRepository};
#[derive(Debug, Clone)]
pub enum ReplacementObjects {
UseWithEnvironmentRefPrefixOrDefault {
allow_disable_via_environment: bool,
},
UseWithRefPrefix {
prefix: PathBuf,
allow_disable_via_environment: bool,
},
Disable,
}
impl Default for ReplacementObjects {
fn default() -> Self {
ReplacementObjects::UseWithEnvironmentRefPrefixOrDefault {
allow_disable_via_environment: true,
}
}
}
impl ReplacementObjects {
fn refs_prefix(self) -> Option<PathBuf> {
use ReplacementObjects::*;
let is_disabled = |allow_env: bool| allow_env && std::env::var_os("GIT_NO_REPLACE_OBJECTS").is_some();
match self {
UseWithEnvironmentRefPrefixOrDefault {
allow_disable_via_environment,
} => {
if is_disabled(allow_disable_via_environment) {
return None;
};
PathBuf::from(std::env::var("GIT_REPLACE_REF_BASE").unwrap_or_else(|_| "refs/replace/".into())).into()
}
UseWithRefPrefix {
prefix,
allow_disable_via_environment,
} => {
if is_disabled(allow_disable_via_environment) {
return None;
};
prefix.into()
}
Disable => None,
}
}
}
#[derive(Default, Clone)]
pub struct Options {
object_store_slots: git_odb::store::init::Slots,
replacement_objects: ReplacementObjects,
permissions: Permissions,
}
#[derive(Default, Clone)]
#[allow(dead_code)]
pub(crate) struct EnvironmentOverrides {
worktree_dir: Option<PathBuf>,
git_dir: Option<PathBuf>,
}
impl EnvironmentOverrides {
fn from_env() -> Result<Self, crate::permission::env_var::resource::Error> {
let mut worktree_dir = None;
if let Some(path) = std::env::var_os("GIT_WORK_TREE") {
worktree_dir = PathBuf::from(path).into();
}
let mut git_dir = None;
if let Some(path) = std::env::var_os("GIT_DIR") {
git_dir = PathBuf::from(path).into();
}
Ok(EnvironmentOverrides { worktree_dir, git_dir })
}
}
impl Options {
pub fn object_store_slots(mut self, slots: git_odb::store::init::Slots) -> Self {
self.object_store_slots = slots;
self
}
pub fn replacement_objects(mut self, config: ReplacementObjects) -> Self {
self.replacement_objects = config;
self
}
pub fn permissions(mut self, permissions: crate::Permissions) -> Self {
self.permissions = permissions;
self
}
pub fn open(self, path: impl Into<std::path::PathBuf>) -> Result<ThreadSafeRepository, Error> {
ThreadSafeRepository::open_opts(path, self)
}
}
impl git_sec::trust::DefaultForLevel for Options {
fn default_for_level(level: Trust) -> Self {
match level {
git_sec::Trust::Full => Options {
object_store_slots: Default::default(),
replacement_objects: Default::default(),
permissions: Permissions::all(),
},
git_sec::Trust::Reduced => Options {
object_store_slots: git_odb::store::init::Slots::Given(32),
replacement_objects: ReplacementObjects::Disable,
permissions: Default::default(),
},
}
}
}
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error {
#[error(transparent)]
Config(#[from] crate::config::Error),
#[error(transparent)]
NotARepository(#[from] git_discover::is_git::Error),
#[error(transparent)]
ObjectStoreInitialization(#[from] std::io::Error),
#[error("The git directory at '{}' is considered unsafe as it's not owned by the current user.", .path.display())]
UnsafeGitDir { path: std::path::PathBuf },
#[error(transparent)]
EnvironmentAccessDenied(#[from] crate::permission::env_var::resource::Error),
}
impl ThreadSafeRepository {
pub fn open(path: impl Into<std::path::PathBuf>) -> Result<Self, Error> {
Self::open_opts(path, Options::default())
}
pub fn open_opts(path: impl Into<std::path::PathBuf>, options: Options) -> Result<Self, Error> {
let (path, kind) = {
let path = path.into();
match git_discover::is_git(&path) {
Ok(kind) => (path, kind),
Err(_err) => {
let git_dir = path.join(".git");
git_discover::is_git(&git_dir).map(|kind| (git_dir, kind))?
}
}
};
let (git_dir, worktree_dir) =
git_discover::repository::Path::from_dot_git_dir(path, kind).into_repository_and_work_tree_directories();
ThreadSafeRepository::open_from_paths(git_dir, worktree_dir, options)
}
pub fn open_with_environment_overrides(
fallback_directory: impl Into<PathBuf>,
trust_map: git_sec::trust::Mapping<Options>,
) -> Result<Self, Error> {
let overrides = EnvironmentOverrides::from_env()?;
let (path, path_kind): (PathBuf, _) = match overrides.git_dir {
Some(git_dir) => git_discover::is_git(&git_dir).map(|kind| (git_dir, kind))?,
None => {
let fallback_directory = fallback_directory.into();
git_discover::is_git(&fallback_directory).map(|kind| (fallback_directory, kind))?
}
};
let (git_dir, worktree_dir) = git_discover::repository::Path::from_dot_git_dir(path, path_kind)
.into_repository_and_work_tree_directories();
let worktree_dir = worktree_dir.or(overrides.worktree_dir);
let trust = git_sec::Trust::from_path_ownership(&git_dir)?;
let options = trust_map.into_value_by_level(trust);
ThreadSafeRepository::open_from_paths(git_dir, worktree_dir, options)
}
pub(crate) fn open_from_paths(
git_dir: PathBuf,
mut worktree_dir: Option<PathBuf>,
Options {
object_store_slots,
replacement_objects,
permissions: Permissions {
git_dir: git_dir_perm,
env,
},
}: Options,
) -> Result<Self, Error> {
if *git_dir_perm != git_sec::ReadWrite::all() {
return Err(Error::UnsafeGitDir { path: git_dir });
}
let common_dir = git_discover::path::from_plain_file(git_dir.join("commondir"))
.transpose()?
.map(|cd| git_dir.join(cd));
let common_dir_ref = common_dir.as_deref().unwrap_or(&git_dir);
let config = crate::config::Cache::new(
common_dir_ref,
env.xdg_config_home.clone(),
env.home.clone(),
crate::path::install_dir().ok().as_deref(),
)?;
match worktree_dir {
None if !config.is_bare => {
worktree_dir = Some(git_dir.parent().expect("parent is always available").to_owned());
}
Some(_) => {
}
None => {}
}
let refs = {
let reflog = if worktree_dir.is_none() {
git_ref::store::WriteReflog::Disable
} else {
git_ref::store::WriteReflog::Normal
};
match &common_dir {
Some(common_dir) => {
crate::RefStore::for_linked_worktree(&git_dir, common_dir, reflog, config.object_hash)
}
None => crate::RefStore::at(&git_dir, reflog, config.object_hash),
}
};
let replacements = replacement_objects
.clone()
.refs_prefix()
.and_then(|prefix| {
let platform = refs.iter().ok()?;
let iter = platform.prefixed(&prefix).ok()?;
let prefix = prefix.to_str()?;
let replacements = iter
.filter_map(Result::ok)
.filter_map(|r: git_ref::Reference| {
let target = r.target.try_id()?.to_owned();
let source =
git_hash::ObjectId::from_hex(r.name.as_bstr().strip_prefix(prefix.as_bytes())?).ok()?;
Some((source, target))
})
.collect::<Vec<_>>();
Some(replacements)
})
.unwrap_or_default();
let linked_worktree_options = Options {
object_store_slots,
replacement_objects,
permissions: Permissions {
env,
git_dir: git_dir_perm,
},
};
Ok(ThreadSafeRepository {
objects: OwnShared::new(git_odb::Store::at_opts(
common_dir_ref.join("objects"),
replacements,
git_odb::store::init::Options {
slots: object_store_slots,
object_hash: config.object_hash,
use_multi_pack_index: config.use_multi_pack_index,
},
)?),
common_dir,
refs,
work_tree: worktree_dir,
config,
linked_worktree_options,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn size_of_options() {
assert_eq!(
std::mem::size_of::<Options>(),
56,
"size shouldn't change without us knowing"
);
}
}