gix_index/entry/stat.rs
1use std::{
2 cmp::Ordering,
3 time::{SystemTime, SystemTimeError},
4};
5
6use filetime::FileTime;
7
8use crate::entry::Stat;
9
10impl Stat {
11 /// Detect whether this stat entry is racy if stored in a file index with `timestamp`.
12 ///
13 /// An index entry is considered racy if it's `mtime` is larger or equal to the index `timestamp`.
14 /// The index `timestamp` marks the point in time before which we definitely resolved the racy git problem
15 /// for all index entries so any index entries that changed afterwards will need to be examined for
16 /// changes by actually reading the file from disk at least once.
17 pub fn is_racy(
18 &self,
19 timestamp: FileTime,
20 Options {
21 check_stat, use_nsec, ..
22 }: Options,
23 ) -> bool {
24 match timestamp.unix_seconds().cmp(&i64::from(self.mtime.secs)) {
25 Ordering::Less => true,
26 Ordering::Equal if use_nsec && check_stat => timestamp.nanoseconds() <= self.mtime.nsecs,
27 Ordering::Equal => true,
28 Ordering::Greater => false,
29 }
30 }
31
32 /// Compares the stat information of two index entries.
33 ///
34 /// Intuitively this is basically equivalent to `self == other`.
35 /// However there a lot of nobs in git that tweak whether certain stat information is used when checking
36 /// equality, see [`Options`].
37 /// This function respects those options while performing the stat comparison and may therefore ignore some fields.
38 pub fn matches(
39 &self,
40 other: &Self,
41 Options {
42 trust_ctime,
43 check_stat,
44 use_nsec,
45 use_stdev,
46 }: Options,
47 ) -> bool {
48 if self.mtime.secs != other.mtime.secs {
49 return false;
50 }
51 if check_stat && use_nsec && self.mtime.nsecs != other.mtime.nsecs {
52 return false;
53 }
54
55 if self.size != other.size {
56 return false;
57 }
58
59 if trust_ctime {
60 if self.ctime.secs != other.ctime.secs {
61 return false;
62 }
63 if check_stat && use_nsec && self.ctime.nsecs != other.ctime.nsecs {
64 return false;
65 }
66 }
67
68 if check_stat {
69 if use_stdev && self.dev != other.dev {
70 return false;
71 }
72 self.ino == other.ino && self.gid == other.gid && self.uid == other.uid
73 } else {
74 true
75 }
76 }
77
78 /// Creates stat information from file metadata.
79 ///
80 /// The information passed to this function should originate from a function like
81 /// `symlink_metadata`/`lstat` or `File::metadata`/`fstat`.
82 ///
83 /// The data are adjusted for use in the index, using default values of fields that are not
84 /// meaningful on the target operating system or that are unavailable, and truncating data
85 /// where doing so does not lose essential information for keeping track of file status.
86 pub fn from_fs(stat: &crate::fs::Metadata) -> Result<Stat, SystemTimeError> {
87 let mtime = stat.modified().unwrap_or(std::time::UNIX_EPOCH);
88 let ctime = stat.created().unwrap_or(std::time::UNIX_EPOCH);
89
90 #[cfg(windows)]
91 let res = Stat {
92 mtime: mtime.try_into()?,
93 ctime: ctime.try_into()?,
94 dev: 0,
95 ino: 0,
96 uid: 0,
97 gid: 0,
98 // Truncation to 32 bits is on purpose (git does the same).
99 size: stat.len() as u32,
100 };
101 #[cfg(not(windows))]
102 let res = {
103 Stat {
104 mtime: mtime.try_into().unwrap_or_default(),
105 ctime: ctime.try_into().unwrap_or_default(),
106 // Truncating the device and inode numbers to 32 bits should be fine even on
107 // targets where they are represented as 64 bits, since we do not use them
108 // precisely for tracking changes and we do not map them back to the inode.
109 dev: stat.dev() as u32,
110 ino: stat.ino() as u32,
111 uid: stat.uid(),
112 gid: stat.gid(),
113 // Truncation to 32 bits is on purpose (git does the same).
114 size: stat.len() as u32,
115 }
116 };
117
118 Ok(res)
119 }
120}
121
122impl TryFrom<SystemTime> for Time {
123 type Error = SystemTimeError;
124 fn try_from(s: SystemTime) -> Result<Self, SystemTimeError> {
125 let d = s.duration_since(std::time::UNIX_EPOCH)?;
126 Ok(Time {
127 // truncation to 32 bits is on purpose (we only compare the low bits)
128 secs: d.as_secs() as u32,
129 nsecs: d.subsec_nanos(),
130 })
131 }
132}
133
134impl From<Time> for SystemTime {
135 fn from(s: Time) -> Self {
136 std::time::UNIX_EPOCH + std::time::Duration::new(s.secs.into(), s.nsecs)
137 }
138}
139
140/// The time component in a [`Stat`] struct.
141#[derive(Debug, Default, PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Copy)]
142#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
143pub struct Time {
144 /// The amount of seconds elapsed since EPOCH.
145 pub secs: u32,
146 /// The amount of nanoseconds elapsed in the current second, ranging from 0 to 999.999.999 .
147 pub nsecs: u32,
148}
149
150impl From<FileTime> for Time {
151 fn from(value: FileTime) -> Self {
152 Time {
153 secs: value.unix_seconds().try_into().expect("can't represent non-unix times"),
154 nsecs: value.nanoseconds(),
155 }
156 }
157}
158
159impl PartialEq<FileTime> for Time {
160 fn eq(&self, other: &FileTime) -> bool {
161 *self == Time::from(*other)
162 }
163}
164
165impl PartialOrd<FileTime> for Time {
166 fn partial_cmp(&self, other: &FileTime) -> Option<Ordering> {
167 self.partial_cmp(&Time::from(*other))
168 }
169}
170
171/// Configuration for comparing stat entries
172#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
173pub struct Options {
174 /// If true, a files creation time is taken into consideration when checking if a file changed.
175 /// Can be set to false in case other tools alter the creation time in ways that interfere with our operation.
176 ///
177 /// Default `true`.
178 pub trust_ctime: bool,
179 /// If true, all stat fields will be used when checking for up-to-date'ness of the entry. Otherwise
180 /// nano-second parts of mtime and ctime,uid, gid, inode and device number _will not_ be used, leaving only
181 /// the whole-second part of ctime and mtime and the file size to be checked.
182 ///
183 /// Default `true`.
184 pub check_stat: bool,
185 /// Whether to compare nano secs when comparing timestamps. This currently
186 /// leads to many false positives on linux and is therefore disabled there.
187 ///
188 /// Default `false`
189 pub use_nsec: bool,
190 /// Whether to compare network devices secs when comparing timestamps.
191 /// Disabled by default because this can cause many false positives on network
192 /// devices where the device number is not stable
193 ///
194 /// Default `false`.
195 pub use_stdev: bool,
196}
197
198impl Default for Options {
199 fn default() -> Self {
200 Self {
201 trust_ctime: true,
202 check_stat: true,
203 use_nsec: false,
204 use_stdev: false,
205 }
206 }
207}