Skip to content

Commit

Permalink
acquiring session files
Browse files Browse the repository at this point in the history
  • Loading branch information
kirawi committed Jan 19, 2023
1 parent e9af9df commit 2cb2683
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
5 changes: 5 additions & 0 deletions helix-view/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::{
graphics::{CursorKind, Rect},
info::Info,
input::KeyEvent,
session::Session,
theme::{self, Theme},
tree::{self, Tree},
Align, Document, DocumentId, View, ViewId,
Expand Down Expand Up @@ -829,6 +830,10 @@ impl Editor {
}
}

pub fn session(&self) -> anyhow::Result<Session> {
Session::new(std::env::current_dir()?)
}

/// Current editing mode for the [`Editor`].
pub fn mode(&self) -> Mode {
self.mode
Expand Down
34 changes: 29 additions & 5 deletions helix-view/src/session.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,40 @@
use std::{
fs::{File, OpenOptions},
path::{Path, PathBuf},
path::PathBuf,
};

use anyhow::Result;
use anyhow::{Context, Result};
use sha1_smol::Sha1;

pub struct Session {
path: PathBuf,
guard: Option<FileLock>,
}

impl Session {
// TODO: Allow custom session names to be passed.
pub fn new(path: PathBuf) -> Result<Self> {
let bytes = sys::path_as_bytes(path.as_path());
let hash = Sha1::from(bytes).digest().to_string();
let path = helix_loader::cache_dir().join(hash);
Ok(Self { path })
let path = helix_loader::cache_dir().join("sessions").join(hash);
Ok(Self { path, guard: None })
}

// TODO: Return a FileLockGuard instead.
pub fn get(&mut self, filename: String) -> Result<File> {
if self.guard.is_none() {
let lock = FileLock::new(self.path.join(".helix.lock"))?;
lock.lock()?;

self.guard = Some(lock);
}

OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(self.path.join(filename))
.context("failed to open file")
}
}

Expand All @@ -24,7 +43,12 @@ pub struct FileLock {
}

impl FileLock {
pub fn new(path: &Path) -> Result<Self> {
pub fn new(path: PathBuf) -> Result<Self> {
if let Some(parent) = path.parent() {
if !parent.exists() {
std::fs::DirBuilder::new().recursive(true).create(parent)?;
}
}
let file = OpenOptions::new().write(true).create(true).open(path)?;
Ok(Self { file })
}
Expand Down

0 comments on commit 2cb2683

Please sign in to comment.