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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
 * Copyright 2021 Kier Ada Davis
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use serde::{de::DeserializeOwned, Serialize};
use std::borrow::Cow;
use std::convert::Infallible;
use std::marker::PhantomData;
use std::os::unix::ffi::OsStringExt;
use std::path::Path;

pub trait Codec<K> {
  type Accepted: ?Sized;
  type EncodeError: std::error::Error + 'static;
  fn encode<'v>(key: &K, value: &'v Self::Accepted) -> Result<Cow<'v, [u8]>, Self::EncodeError>;
  type Produced;
  type DecodeError: std::error::Error + 'static;
  fn decode(key: &K, value: &[u8]) -> Result<Self::Produced, Self::DecodeError>;
}

#[derive(Debug)]
pub struct Raw;
impl<K> Codec<K> for Raw {
  type Accepted = [u8];
  type EncodeError = Infallible;
  fn encode<'v>(_: &K, value: &'v [u8]) -> Result<Cow<'v, [u8]>, Infallible> {
    Ok(Cow::Borrowed(value))
  }
  type Produced = Vec<u8>;
  type DecodeError = Infallible;
  fn decode(_: &K, value: &[u8]) -> Result<Vec<u8>, Infallible> {
    Ok(value.to_vec())
  }
}

#[derive(Debug)]
pub struct Toml<V: 'static>(PhantomData<&'static V>);
impl<K, V> Codec<K> for Toml<V>
where
  V: Serialize + DeserializeOwned,
{
  type Accepted = V;
  type EncodeError = toml::ser::Error;
  fn encode<'v>(_: &K, value: &'v V) -> Result<Cow<'v, [u8]>, toml::ser::Error> {
    toml::to_vec(value).map(Cow::Owned)
  }
  type Produced = V;
  type DecodeError = toml::de::Error;
  fn decode(_: &K, value: &[u8]) -> Result<V, toml::de::Error> {
    toml::from_slice(value)
  }
}

pub trait Key: Sized {
  fn to_path(&self) -> Cow<Path>;
  fn from_path(path: &Path) -> Option<Self>;
  type Codec: Codec<Self>;
}

macro_rules! Accepted {
  ($K:ty) => {
    <<$K as Key>::Codec as Codec<$K>>::Accepted
  };
}
macro_rules! Produced {
  ($K:ty) => {
    <<$K as Key>::Codec as Codec<$K>>::Produced
  };
}

pub struct Store {
  repo: git2::Repository,
}
impl std::fmt::Debug for Store {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    f.debug_struct("Store")
      .field("repo", &self.repo.path())
      .finish()
  }
}
pub fn open<P: AsRef<Path>>(path: P) -> Result<Store, Error> {
  Store::open(path)
}
impl Store {
  pub fn open<P: AsRef<Path>>(path: P) -> Result<Store, Error> {
    use git2::ErrorCode::NotFound;
    let repo = match git2::Repository::open(path.as_ref()) {
      Err(err) if err.code() == NotFound => git2::Repository::init_bare(path),
      res => res,
    }
    .map_err(Error::git("open repository"))?;
    Ok(Store { repo })
  }
  pub fn current(&self) -> Result<Version, Error> {
    use git2::ErrorCode::UnbornBranch;
    let reference = match self.repo.head() {
      Err(err) if err.code() == UnbornBranch => return Version::new(self, None),
      res => res,
    }
    .map_err(Error::git("get HEAD"))?;
    let commit = reference
      .peel_to_commit()
      .map_err(Error::git("resolve HEAD ref to commit"))?;
    Version::new(self, Some(commit))
  }
  pub fn set_current<'repo>(&'repo self, version: &Version<'repo>) -> Result<(), Error> {
    match version.commit.as_ref() {
      None => panic!("not implemented"),
      Some(commit) => {
        const REFERENCE_NAME: &'static str = "refs/heads/master";
        let message = commit
          .summary_bytes()
          .map_or("[sakaagari] update".into(), String::from_utf8_lossy);
        self
          .repo
          .reference(REFERENCE_NAME, commit.id(), true, message.as_ref())
          .map_err(Error::git("create/overwrite HEAD ref"))?;
        self
          .repo
          .set_head(REFERENCE_NAME)
          .map_err(Error::git("set HEAD"))
      }
    }
  }
}

mod internal {
  use super::Key;
  use std::ffi::OsString;
  use std::os::unix::ffi::OsStringExt;
  use std::path::PathBuf;
  pub trait Access {
    fn repo(&self) -> &git2::Repository;
    fn index(&self) -> &git2::Index;
    fn blobs<'a, K: Key>(&'a self) -> Box<dyn Iterator<Item = (K, git2::Oid)> + 'a> {
      Box::new(self.index().iter().filter_map(|entry| match entry.mode {
        0o100644 | 0o100755 => {
          let path = PathBuf::from(OsString::from_vec(entry.path));
          let oid = entry.id;
          K::from_path(&path).map(move |key| (key, oid))
        }
        _ => None,
      }))
    }
  }
  pub trait AccessMut: Access {
    fn index_mut(&mut self) -> &mut git2::Index;
  }
}
pub trait Access: internal::Access {
  fn get<K: Key>(&self, key: &K) -> Result<Produced!(K), Error> {
    let entry = self
      .index()
      .get_path(&key.to_path(), 0)
      .ok_or(Error::NotFound)?;
    let blob = self
      .repo()
      .find_blob(entry.id)
      .map_err(Error::git("get blob from index entry"))?;
    K::Codec::decode(key, blob.content()).map_err(Error::decode)
  }
  fn keys<'a, K: Key + 'a>(&'a self) -> Box<dyn Iterator<Item = K> + 'a> {
    Box::new(self.blobs().map(|pair| pair.0))
  }
  fn iter<'a, K: Key + 'a>(
    &'a self,
  ) -> Box<dyn Iterator<Item = Result<(K, Produced!(K)), Error>> + 'a> {
    Box::new(self.blobs().map(move |(key, oid)| {
      let blob = self
        .repo()
        .find_blob(oid)
        .map_err(Error::git("get blob by id while iterating"))?;
      let value = K::Codec::decode(&key, blob.content()).map_err(Error::decode)?;
      Ok((key, value))
    }))
  }
  fn values<'a, K: Key + 'a>(
    &'a self,
  ) -> Box<dyn Iterator<Item = Result<Produced!(K), Error>> + 'a> {
    Box::new(self.iter::<K>().map(|result| result.map(|pair| pair.1)))
  }
}
pub trait AccessMut: internal::AccessMut {
  fn put<K: Key>(&mut self, key: &K, value: &Accepted!(K)) -> Result<(), Error> {
    let contents = K::Codec::encode(key, value).map_err(Error::encode)?;
    let blob_id = self
      .repo()
      .blob(&contents)
      .map_err(Error::git("create blob"))?;
    let now = current_index_time();
    let entry = git2::IndexEntry {
      ctime: now,
      mtime: now,
      dev: 0,
      ino: 0,
      mode: 0o100644,
      uid: 0,
      gid: 0,
      file_size: contents.len() as u32,
      id: blob_id,
      flags: 0,
      flags_extended: 0,
      path: key.to_path().into_owned().into_os_string().into_vec(),
    };
    self
      .index_mut()
      .add(&entry)
      .map_err(Error::git("insert entry into index"))
  }
  fn delete<K: Key>(&mut self, key: &K) -> Result<(), Error> {
    self
      .index_mut()
      .remove(&key.to_path(), 0)
      .map_err(Error::git("remove entry from index"))
  }
}

pub struct Version<'repo> {
  store: &'repo Store,
  commit: Option<git2::Commit<'repo>>,
  index: git2::Index,
}
impl<'repo> Version<'repo> {
  fn new(store: &'repo Store, commit: Option<git2::Commit<'repo>>) -> Result<Self, Error> {
    Ok(Version {
      index: index_from_commit(commit.as_ref())?,
      store,
      commit,
    })
  }
  fn commit_id(&self) -> Option<git2::Oid> {
    self.commit.as_ref().map(|c| c.id())
  }
  pub fn derive<F>(&self, f: F) -> Result<Version<'repo>, Error>
  where
    F: for<'tx> FnOnce(&'tx mut Transaction<'repo>) -> Result<CommitMessage, Error>,
  {
    let mut tx = Transaction {
      store: self.store,
      index: index_from_commit(self.commit.as_ref())?,
    };
    let commit_message = f(&mut tx)?;
    let signature = self
      .store
      .repo
      .signature()
      .map_err(Error::git("create signature"))?;
    let tree_id = tx
      .index
      .write_tree_to(&self.store.repo)
      .map_err(Error::git("create tree from index"))?;
    let tree = self
      .store
      .repo
      .find_tree(tree_id)
      .map_err(Error::git("get created tree"))?;
    Ok(Version::new(
      self.store,
      Some(
        self
          .store
          .repo
          .find_commit(
            self
              .store
              .repo
              .commit(
                None,
                &signature,
                &signature,
                commit_message.as_ref(),
                &tree,
                &self.commit.iter().collect::<Vec<_>>(),
              )
              .map_err(Error::git("create commit"))?,
          )
          .map_err(Error::git("get created commit"))?,
      ),
    )?)
  }
}
impl<'repo> internal::Access for Version<'repo> {
  fn repo(&self) -> &git2::Repository {
    &self.store.repo
  }
  fn index(&self) -> &git2::Index {
    &self.index
  }
}
impl<'repo> Access for Version<'repo> {}
impl<'repo> Clone for Version<'repo> {
  fn clone(&self) -> Self {
    Version::new(self.store, self.commit.clone()).unwrap()
  }
}
impl<'repo> std::fmt::Debug for Version<'repo> {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    f.debug_struct("Version")
      .field("store", &self.store)
      .field("commit", &self.commit)
      .finish()
  }
}
impl<'repo> PartialEq for Version<'repo> {
  fn eq(&self, other: &Self) -> bool {
    self.commit_id() == other.commit_id()
  }
}
impl<'repo> Eq for Version<'repo> {}

pub struct Transaction<'repo> {
  store: &'repo Store,
  index: git2::Index,
}
impl<'repo> internal::Access for Transaction<'repo> {
  fn repo(&self) -> &git2::Repository {
    &self.store.repo
  }
  fn index(&self) -> &git2::Index {
    &self.index
  }
}
impl<'repo> internal::AccessMut for Transaction<'repo> {
  fn index_mut(&mut self) -> &mut git2::Index {
    &mut self.index
  }
}
impl<'repo> Access for Transaction<'repo> {}
impl<'repo> AccessMut for Transaction<'repo> {}
impl<'repo> std::fmt::Debug for Transaction<'repo> {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    f.debug_struct("Transaction")
      .field("store", &self.store)
      .finish()
  }
}

fn index_from_commit<'repo>(commit: Option<&git2::Commit<'repo>>) -> Result<git2::Index, Error> {
  let mut index = git2::Index::new().map_err(Error::git("create new index"))?;
  match commit {
    Some(commit) => index
      .read_tree(&commit.tree().map_err(Error::git("get tree from commit"))?)
      .map_err(Error::git("populate index from tree"))?,
    None => {}
  }
  Ok(index)
}

fn current_index_time() -> git2::IndexTime {
  use std::time::SystemTime;
  let t = SystemTime::now()
    .duration_since(SystemTime::UNIX_EPOCH)
    .unwrap();
  git2::IndexTime::new(t.as_secs() as i32, t.subsec_nanos() as u32)
}

pub type CommitMessage = String;

#[derive(Debug)]
pub enum Error {
  NotFound,
  Git(git2::Error, Cow<'static, str>),
  Encode(Box<dyn std::error::Error>),
  Decode(Box<dyn std::error::Error>),
}
impl Error {
  pub fn git<S: Into<Cow<'static, str>>>(what: S) -> impl FnOnce(git2::Error) -> Self {
    let what = what.into();
    move |err| Error::Git(err, what)
  }
  pub fn encode<E: std::error::Error + 'static>(err: E) -> Self {
    Self::Encode(Box::new(err))
  }
  pub fn decode<E: std::error::Error + 'static>(err: E) -> Self {
    Self::Decode(Box::new(err))
  }
}
impl std::fmt::Display for Error {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    match self {
      Error::NotFound => write!(f, "not found"),
      Error::Git(err, what) => write!(f, "internal git error when attempting to {}: {}", what, err),
      Error::Encode(err) => write!(f, "failed to encode value: {}", err),
      Error::Decode(err) => write!(f, "failed to decode value: {}", err),
    }
  }
}
impl std::error::Error for Error {}