Skip to content

Commit

Permalink
Allow loading from arbitrary directories, add .rqst-token file
Browse files Browse the repository at this point in the history
  • Loading branch information
willcrichton committed Aug 9, 2024
1 parent 88deb5e commit 21dcece
Show file tree
Hide file tree
Showing 6 changed files with 366 additions and 112 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ anyhow = "1.0.86"
dioxus = { version = "0.5.1", features = ["desktop"] }
dioxus-logger = "0.5.1"
futures-util = "0.3.30"
home = "0.5.9"
http = "1.1.0"
octocrab = "0.38.0"
parking_lot = "0.12.3"
Expand All @@ -21,4 +22,4 @@ tracing = "0.1.40"

[profile.release]
strip = true
lto = true
lto = true
34 changes: 33 additions & 1 deletion assets/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,36 @@ h1 {

.gh-links a:not(:first-child) {
margin-left: 0.5rem;
}
}

input[type=file] {
display: none;
}

button, label {
display: inline-block;
appearance: none;
background: #eee;
border: 1px solid #aaa;
border-radius: 4px;
padding: 3px 5px;
cursor: pointer;

&:hover {
background-color: #fafafa;
}
}

.controls {
display: flex;
gap: 1rem;
}

.new-quest {
display: flex;
flex-direction: column;
gap: 1rem;
}

/* .working-dir {
} */
73 changes: 61 additions & 12 deletions src/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use octocrab::{
};
use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
use serde_json::json;
use std::{process::Command, sync::Arc, time::Duration};
use std::{env, fs, process::Command, sync::Arc, time::Duration};
use tokio::{time::timeout, try_join};

pub struct GithubRepo {
Expand Down Expand Up @@ -262,19 +262,68 @@ impl GithubRepo {
}
}

pub fn get_github_token() -> Result<String> {
let token_output = Command::new("gh")
.args(["auth", "token"])
.output()
.context("Failed to run `gh auth token`")?;
let token = String::from_utf8(token_output.stdout)?;
let token_clean = token.trim_end().to_string();
Ok(token_clean)
pub enum GithubToken {
Found(String),
Error(anyhow::Error),
Missing,
}

pub fn init_octocrab() -> Result<()> {
let token = get_github_token()?;
let crab_inst = Octocrab::builder().personal_token(token).build()?;
macro_rules! token_try {
($e:expr) => {{
match $e {
Ok(x) => x,
Err(e) => return GithubToken::Error(e.into()),
}
}};
}

fn read_github_token_from_fs() -> GithubToken {
let home = match home::home_dir() {
Some(dir) => dir,
None => return GithubToken::Missing,
};
let path = home.join(".rqst-token");
if path.exists() {
let token = token_try!(fs::read_to_string(path));
GithubToken::Found(token.trim_end().to_string())
} else {
GithubToken::Missing
}
}

fn generate_github_token_from_cli() -> GithubToken {
let shell = env::var("SHELL").unwrap();
let which_status = Command::new(&shell).args(["-c", "which gh"]).status();
match which_status {
Ok(status) => {
if status.success() {
let token_output = token_try!(Command::new(shell)
.args(["-c", "gh auth token"])
.output()
.context("Failed to run `gh auth token`"));
let token = token_try!(String::from_utf8(token_output.stdout));
let token_clean = token.trim_end().to_string();
GithubToken::Found(token_clean)
} else {
GithubToken::Missing
}
}
Err(err) => GithubToken::Error(err.into()),
}
}

pub fn get_github_token() -> GithubToken {
match read_github_token_from_fs() {
GithubToken::Missing => generate_github_token_from_cli(),
result => result,
}
}

pub fn init_octocrab(token: &str) -> Result<()> {
println!("ok {token:?}");
let crab_inst = Octocrab::builder()
.personal_token(token.to_string())
.build()?;
octocrab::initialise(crab_inst);
Ok(())
}
52 changes: 35 additions & 17 deletions src/quest.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
use std::{collections::HashMap, env, process::Command, time::Duration};
use std::{
collections::HashMap,
env::{self, set_current_dir},
path::{Path, PathBuf},
process::Command,
time::Duration,
};

use crate::{
git::GitRepo,
Expand All @@ -17,14 +23,32 @@ use regex::Regex;
use serde::{Deserialize, Serialize};
use tokio::{time::sleep, try_join};

#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct QuestConfig {
pub title: String,
pub author: String,
pub repo: String,
pub stages: Vec<StageConfig>,
}

impl QuestConfig {
pub fn load(dir: impl AsRef<Path>) -> Result<Self> {
let output = Command::new("git")
.args(["show", "upstream/meta:rqst.toml"])
.current_dir(dir)
.output()
.context("git failed")?;
ensure!(
output.status.success(),
"git exited with non-zero status code"
);
let stdout = String::from_utf8(output.stdout)?.trim().to_string();
let config = toml::de::from_str::<QuestConfig>(&stdout)?;

Ok(config)
}
}

#[derive(Clone, Debug)]
pub struct QuestState {
pub stage: Stage,
Expand All @@ -39,26 +63,12 @@ pub struct Quest {
origin_git: GitRepo,
stage_index: HashMap<String, usize>,

pub dir: PathBuf,
pub config: QuestConfig,
pub state_signal: SyncSignal<Option<QuestState>>,
pub stages: Vec<Stage>,
}

pub fn load_config_from_current_dir() -> Result<QuestConfig> {
let output = Command::new("git")
.args(["show", "upstream/meta:rqst.toml"])
.output()
.context("git failed")?;
ensure!(
output.status.success(),
"git exited with non-zero status code"
);
let stdout = String::from_utf8(output.stdout)?.trim().to_string();
let config = toml::de::from_str::<QuestConfig>(&stdout)?;

Ok(config)
}

pub async fn load_config_from_remote(owner: &str, repo: &str) -> Result<QuestConfig> {
let items = octocrab::instance()
.repos(owner, repo)
Expand All @@ -83,6 +93,7 @@ async fn load_user() -> Result<String> {

impl Quest {
pub async fn load(
dir: PathBuf,
config: QuestConfig,
state_signal: SyncSignal<Option<QuestState>>,
) -> Result<Self> {
Expand All @@ -102,6 +113,7 @@ impl Quest {
.collect::<HashMap<_, _>>();

let q = Quest {
dir,
user,
config,
upstream,
Expand All @@ -115,6 +127,12 @@ impl Quest {
try_join!(q.infer_state_update(), q.origin.fetch(), q.upstream.fetch())
.context("Failed to load quest data")?;

if q.dir.exists() {
set_current_dir(&q.dir)?;
} else {
set_current_dir(q.dir.parent().unwrap())?;
}

Ok(q)
}

Expand Down
Loading

0 comments on commit 21dcece

Please sign in to comment.