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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use serde_json;
use url::percent_encoding::{utf8_percent_encode, PATH_SEGMENT_ENCODE_SET};

#[cfg(not(target_arch = "wasm32"))]
use rand;
#[cfg(not(target_arch = "wasm32"))]
use libpijul;
#[cfg(not(target_arch = "wasm32"))]
use libpijul::{
    fs_representation::{RepoPath, RepoRoot},
    graph::LineBuffer,
    patch::Record,
    DiffAlgorithm, Key, PatchId, RecordState, Transaction, Value,
};
#[cfg(not(target_arch = "wasm32"))]
use std::collections::HashMap;
#[cfg(not(target_arch = "wasm32"))]
use url::percent_encoding::percent_decode;

mod msg;
mod entry_contents;
pub use self::msg::Msg;
pub use self::entry_contents::*;

/// Represents the application state
#[derive(Clone, Serialize, Deserialize)]
pub struct State {
    /// The current URL path
    path: String,
    /// The relative repository path of the current entry
    entry_path: PathBuf,
    /// Information about the patches applied to the current entry
    patches: Vec<PatchHeader>,
    selected_patch: Option<String>,
    /// Info about the direct children of the current directory
    dir_contents: Option<Vec<DirEntry>>,
    /// The contents of a file
    file_contents: Option<String>,
    /// Represents whether to render a markdown file with pulldown_cmark or
    /// just display the source code for all markdown files in `FileView`.
    render_md: bool,
    /// Whether or not to show the changes made from the last patch
    diff_mode: bool,
}

impl State {
    /// Returns a `State` with an initial configuration
    pub fn new() -> State {
        State {
            path: "/".to_string(),
            entry_path: PathBuf::from("./"),
            patches: vec![],
            selected_patch: None,
            dir_contents: None,
            file_contents: None,
            render_md: true,
            diff_mode: false,
        }
    }

    /// Returns a `State` from an existing configuration
    pub fn from_json(state_json: &str) -> State {
        serde_json::from_str(state_json).expect("Unable to deserialize State json")
    }

    /// Serializes this `State` to JSON
    pub fn to_json(&self) -> String {
        serde_json::to_string(&self).expect("Unable to serialize state")
    }
}

impl State {
    /// Commands to update the fields of this `State`
    pub fn msg(&mut self, msg: &Msg) {
        match msg {
            Msg::SetPath(path) => self.set_path(path.to_string()),
            Msg::SetSelectedPatch(selected_patch) => {
                self.selected_patch = selected_patch.to_owned();
            }
            #[cfg(not(target_arch = "wasm32"))]
            Msg::SetEntryContents(encoded_path) => {
                self.set_entry_path(encoded_path.to_string());
                self.set_entry_contents()
            }
            Msg::SetEntryContentsJson(json) => {
                let entry: EntryContents = json
                    .into_serde()
                    .expect("Unable to deserialize EntryContents json");

                self.entry_path = PathBuf::from(entry.path);
                self.dir_contents = entry.dir_contents;
                self.file_contents = entry.file_contents;
                self.patches = entry.patches;
            }
            Msg::ToggleRenderMd => self.toggle_render_md(),
        };
    }

    /// Returns a reference to `self.path`
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Returns a reference to `self.entry_path`
    pub fn entry_path(&self) -> &Path {
        self.entry_path.as_path()
    }

    /// Returns a reference to `self.dir_contents`
    pub fn dir_contents(&self) -> &Option<Vec<DirEntry>> {
        &self.dir_contents
    }

    /// Returns a reference to `self.file_contents`
    pub fn file_contents(&self) -> &Option<String> {
        &self.file_contents
    }

    /// Returns a reference to `self.patches`
    pub fn patches(&self) -> &Vec<PatchHeader> {
        &self.patches
    }

    /// Returns a reference to `self.render_md`
    pub fn render_md(&self) -> &bool {
        &self.render_md
    }

    /// Returns a reference to `self.selected_patch`
    pub fn selected_patch(&self) -> &Option<String> {
        &self.selected_patch
    }

    /// Returns a new EntryContents that is contructed from the
    /// clones of this State's matching fields
    pub fn entry_contents(&self) -> EntryContents {
        EntryContents {
            path:           self.entry_path.clone(),
            patches:        self.patches.clone(),
            selected_patch: self.selected_patch.clone(),
            dir_contents:   self.dir_contents.clone(),
            file_contents:  self.file_contents.clone(),
        }
    }

    /// Whether or not `self.entry_path` ends with a '/' character
    pub fn is_dir(&self) -> bool {
        self.entry_path.to_str().unwrap().ends_with("/")
    }

    /// `self.entry_path` represented as a URL-encoded string, without the prefix "./"
    pub fn encoded_path(&self) -> String {
        let entry_path = self.entry_path.to_str().unwrap()[2..].to_string();
        utf8_percent_encode(&entry_path, PATH_SEGMENT_ENCODE_SET).to_string()
    }
}

impl State {
    /// Sets `self.path` to the specified path
    fn set_path(&mut self, path: String) {
        self.path = path;
    }

    /// Toggles `self.render_md` from `true -> false` or `false -> true`
    fn toggle_render_md(&mut self) {
        self.render_md = !self.render_md
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl State {
    /// Sets `self.entry_path` based on the provided `String`
    fn set_entry_path(&mut self, encoded_path: String) {
        let mut entry_path = "./".to_string();
        // Decode repository path to include '/' characters
        let decoded_path = percent_decode(encoded_path.as_bytes())
            .decode_utf8()
            .expect("unable to decode path as utf8");

        entry_path.push_str(&decoded_path);

        self.entry_path = PathBuf::from(&entry_path);
        if !encoded_path.is_empty() && self.entry_path.is_dir() {
            entry_path.push('/');
            self.entry_path = PathBuf::from(&entry_path);
        }
    }

    /// Sets `self.patches`, `self.dir_contents`, and `self.file_contents`
    /// from `self.entry_path`
    fn set_entry_contents(&mut self) {
        if self.is_dir() {
            self.set_dir_contents();

            // The contents of the current directory's README.md is stored in
            // `file_contents` to render from `DirView`
            let readme_path = self.entry_path().join("README.md");
            self.set_file_contents(readme_path);
        } else {
            self.dir_contents = None;
            self.set_file_contents(self.entry_path().to_owned());
        }

        self.set_patches();
    }

    /// Pushes patches to `self.patches` that have been applied to `self.entry_path`
    /// in the form of `PatchHeader`s
    fn set_patches(&mut self) {
        let repo_root = RepoRoot {
            repo_root: Path::new("./"),
        };
        let repo = repo_root.open_repo(None).unwrap();
        let txn = repo.txn_begin().unwrap();
        let branch = txn.get_branch("master").unwrap();

        let repo_path = repo_root.relativize(&self.entry_path).unwrap().to_owned();

        for (_applied, patchid) in txn.rev_iter_applied(&branch, None) {
            let hash = txn.get_external(patchid).unwrap();

            if self.entry_path != PathBuf::from("./") {
                let inode = if let Ok(inode) = txn.find_inode(&repo_path) {
                    inode
                } else {
                    continue;
                };
                match txn.get_inodes(inode) {
                    Some(file_header) => {
                        if self.is_dir() {
                            let descendants = txn.list_files(inode).unwrap();
                            for descendant in descendants {
                                let d_inode = txn.find_inode(&repo_path.join(&descendant.as_path())).unwrap();
                                let d_file_header = txn.get_inodes(d_inode).unwrap();
                                if txn.get_touched(d_file_header.key, patchid) {
                                    self.patches.push(PatchHeader::from_hash(hash));
                                    break;
                                }
                            }
                            continue;
                        } else if !txn.get_touched(file_header.key, patchid) {
                            continue;
                        }
                    }
                    // This is a new entry
                    None => {
                        self.patches.push(PatchHeader::current_state());
                        break;
                    }
                }
            }
            self.patches.push(PatchHeader::from_hash(hash));
        }
    }

    /// Sets self.dir_contents to a vector of direct children entries
    /// in relation to self.entry_path (the current directory)
    //
    // TODO: handle removed files
    fn set_dir_contents(&mut self) {
        // TODO: need to figure out how to get directory contents of previous patch
        // Prepare to obtain info from Pijul repository
        let repo_root = RepoRoot {
            repo_root: Path::new("./"),
        };
        let repo = repo_root.open_repo(None).unwrap();
        let mut txn = repo.mut_txn_begin(rand::thread_rng()).unwrap();
        let branch = txn.open_branch("master").unwrap();

        // Current directory as a RepoPath in a relative format
        let dir_path = repo_root.relativize(&self.entry_path).unwrap();

        // Temporary variable to hold info about the direct children of
        // the current directory
        let mut dir_contents_map = HashMap::new();

        // Loops through all descendants of the current directory to find
        // direct children entries.
        // TODO: use iter_folder_children instead
        let entries = txn.list_files(txn.find_inode(&dir_path).unwrap()).unwrap();

        let mut changed = false;
        for repo_path in entries {
            // Retrieves the name of the direct child, even if repo_path is a descendant of
            // the direct child
            let name = repo_path
                .components()
                .next()
                .unwrap()
                .as_os_str()
                .to_str()
                .unwrap();

            // Need to make sure the entry hasn't already been added to dir_entries
            if !dir_contents_map.contains_key(name) {
                // Get the change (if any) of repo_path after applying `txn.record()`
                let mut record = RecordState::new();
                txn.record(
                    DiffAlgorithm::default(),
                    &mut record,
                    &branch,
                    &repo_root,
                    &dir_path.join(&repo_path.as_path()),
                )
                .unwrap();
                let (changes, _) = record.finish();

                let (status, latest_patch) = if changes.is_empty() {
                    let mut latest_patch = PatchHeader::current_state();
                    for (_applied, patchid) in txn.rev_iter_applied(&branch, None) {
                        let hash_ext = txn.get_external(patchid).unwrap();
                        let patch = repo_root.read_patch_nochanges(hash_ext).unwrap();

                        let inode = if let Ok(inode) = txn.find_inode(&repo_path) {
                            inode
                        } else {
                            continue;
                        };
                        match txn.get_inodes(inode) {
                            Some(file_header) => {
                                if !txn.get_touched(file_header.key, patchid) {
                                    continue;
                                }
                            }
                            None => {
                                break;
                            }
                        }

                        latest_patch = PatchHeader {
                            hash: hash_ext.to_base58(),
                            name: patch.name,
                            authors: patch.authors,
                            timestamp: patch.timestamp,
                        };
                        break;
                    }

                    (None, latest_patch)
                } else {
                    if !changed {
                        changed = true;

                        // We set the latest patch to "Current State" if we found changes
                        // that affect the current directory's contents.
                        self.patches.push(PatchHeader::current_state());
                    }

                    let status = Some(
                        // Find changes to direct children of the current directory
                        if repo_path.parent() == None
                            || repo_path.parent() == Some(RepoPath(Path::new("")))
                        {
                            match changes[0] {
                                Record::Change   { .. } => Status::Modified,
                                Record::FileAdd  { .. } => Status::Added,
                                Record::FileDel  { .. } => Status::Removed,
                                Record::FileMove { .. } => Status::Moved,
                            }
                        // Find changes to the other descendants of the current directory
                        //
                        // This marks the status of that direct child as `Modified`,
                        // regardless of the change made to the descendant.
                        //
                        // Pijul lists the files in such a way that the above conditional
                        // still catches changes made to the direct child first, before
                        // catching changes made to the direct child's descendants.
                        } else {
                            Status::Modified
                        },
                    );
                    (status, PatchHeader::current_state())
                };

                dir_contents_map.insert(name.to_string(), (status, latest_patch));
            }
        }

        // Turn the HashMap into a Vec
        let mut dir_contents_vec: Vec<DirEntry> = dir_contents_map
            .iter()
            .map(|(name, (status, latest_patch))| DirEntry {
                name: name.to_string(),
                is_dir: dir_path.as_path().join(&name).is_dir(),
                status: status.to_owned(),
                latest_patch: latest_patch.to_owned(),
            })
            .collect();
        // Sort the directory contents alphabetically
        dir_contents_vec.sort_by_key(|entry| entry.name.to_string());
        dir_contents_vec.sort_by_key(|entry| !entry.is_dir);

        self.dir_contents = Some(dir_contents_vec);
    }

    /// Sets self.file_contents to the current state of contents based on the
    /// given file_path
    fn set_file_contents(&mut self, file_path: PathBuf) {
        // TODO: need to figure out how to get file contents of previous patch use retrieve
        // key<patchid>
        let repo_root = RepoRoot {
            repo_root: Path::new("./"),
        };
        let repo = repo_root.open_repo(None).unwrap();
        let txn = repo.txn_begin().unwrap();

        let entry_path = repo_root.relativize(&file_path).unwrap();

        let inode = txn.find_inode(&entry_path);
        if inode.is_ok() {
            let file_header = txn.get_inodes(inode.unwrap()).unwrap();
            let branch = txn.get_branch("master").unwrap();
            let mut graph = txn.retrieve(&branch, file_header.key);
            let mut buf = OutBuffer {
                lines: String::new(),
            };
            txn.output_file(&branch, &mut buf, &mut graph, &mut Vec::new())
                .unwrap();

            self.file_contents = Some(buf.lines);
        } else {
            self.file_contents = None
        }
    }
}

/// The structure that contains file contents when calling `output_file()`
#[cfg(not(target_arch = "wasm32"))]
struct OutBuffer {
    lines: String,
}

#[cfg(not(target_arch = "wasm32"))]
impl<'a, T: 'a + Transaction> LineBuffer<'a, T> for OutBuffer {
    /// Executed for each line of a file, to obtain its contents when calling `output_file()`
    fn output_line(
        &mut self,
        _key: &Key<PatchId>,
        contents: Value<'a, T>,
    ) -> Result<(), libpijul::Error> {
        for chunk in contents {
            self.lines.push_str(&String::from_utf8_lossy(&chunk));
        }
        Ok(())
    }

    /// Executed for conflicting lines, when calling `output_file()`
    fn output_conflict_marker(&mut self, s: &'a str) -> Result<(), libpijul::Error> {
        let conflict_output = format!("Conflict: {}", s);
        self.lines.push_str(&conflict_output);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Tests the serialization and deserialization of the application state
    #[test]
    fn serialize_deserialize() {
        let state_json =
            r#"{"path":"/","entry_path":"./","patches":[],"dir_contents":null,"file_contents":null,"render_md":true,"diff_mode":false}"#;

        let state = State::from_json(state_json);

        assert_eq!(state.to_json(), state_json);
    }
}