Skip to content

Commit

Permalink
feat: add PESDE_ROOT for bin packages
Browse files Browse the repository at this point in the history
  • Loading branch information
daimond113 committed Sep 3, 2024
1 parent 71eacb8 commit d321b8b
Show file tree
Hide file tree
Showing 10 changed files with 188 additions and 151 deletions.
26 changes: 19 additions & 7 deletions src/cli/commands/execute.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use std::{ffi::OsString, process::Command};

use crate::cli::{config::read_config, VersionedPackageName};
use anyhow::Context;
use clap::Args;
use semver::VersionReq;

use crate::cli::{config::read_config, VersionedPackageName};
use pesde::{
linking::generator::generate_bin_linking_module,
manifest::target::TargetKind,
names::PackageName,
source::{
Expand All @@ -14,6 +11,8 @@ use pesde::{
},
Project,
};
use semver::VersionReq;
use std::{env::current_dir, ffi::OsString, io::Write, process::Command};

#[derive(Debug, Args)]
pub struct ExecuteCommand {
Expand Down Expand Up @@ -72,15 +71,28 @@ impl ExecuteCommand {
fs.write_to(tempdir.path(), project.cas_dir(), true)
.context("failed to write package contents")?;

let mut caller =
tempfile::NamedTempFile::new_in(tempdir.path()).context("failed to create tempfile")?;
caller
.write_all(
generate_bin_linking_module(
tempdir.path(),
&format!("{:?}", bin_path.to_path(tempdir.path())),
)
.as_bytes(),
)
.context("failed to write to tempfile")?;

let status = Command::new("lune")
.arg("run")
.arg(bin_path.to_path(tempdir.path()))
.arg(caller.path())
.arg("--")
.args(&self.args)
.current_dir(project.package_dir())
.current_dir(current_dir().context("failed to get current directory")?)
.status()
.context("failed to run script")?;

drop(caller);
drop(tempdir);

std::process::exit(status.code().unwrap_or(1))
Expand Down
11 changes: 3 additions & 8 deletions src/cli/commands/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,17 @@ use pesde::{
errors::ManifestReadError, names::PackageName, scripts::ScriptName, Project, DEFAULT_INDEX_NAME,
};

use crate::cli::config::read_config;
use crate::cli::{config::read_config, HOME_DIR};

#[derive(Debug, Args)]
pub struct InitCommand {}

fn script_contents(path: &Path) -> String {
format!(
concat!(
r#"local process = require("@lune/process")
r#"local process = require("@lune/process")
local home_dir = if process.os == "windows" then process.env.userprofile else process.env.HOME
require(home_dir .. ""#,
"/.",
env!("CARGO_PKG_NAME"),
r#"/scripts/{}")"#,
),
require(home_dir .. "/{HOME_DIR}/scripts/{}"#,
path.display()
)
}
Expand Down
1 change: 0 additions & 1 deletion src/cli/commands/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ fn bin_link_file(alias: &str) -> String {
let prefix = String::new();
#[cfg(unix)]
let prefix = "#!/usr/bin/env -S lune run\n";
// TODO: reimplement workspace support in this
format!(
r#"{prefix}local process = require("@lune/process")
local fs = require("@lune/fs")
Expand Down
26 changes: 19 additions & 7 deletions src/cli/commands/run.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
use std::{ffi::OsString, path::PathBuf, process::Command};

use crate::cli::up_to_date_lockfile;
use anyhow::Context;
use clap::Args;
use relative_path::RelativePathBuf;

use crate::cli::up_to_date_lockfile;
use pesde::{
linking::generator::generate_bin_linking_module,
names::{PackageName, PackageNames},
source::traits::PackageRef,
Project, PACKAGES_CONTAINER_NAME,
};
use relative_path::RelativePathBuf;
use std::{env::current_dir, ffi::OsString, io::Write, path::PathBuf, process::Command};

#[derive(Debug, Args)]
pub struct RunCommand {
Expand All @@ -25,15 +24,28 @@ pub struct RunCommand {
impl RunCommand {
pub fn run(self, project: Project) -> anyhow::Result<()> {
let run = |path: PathBuf| {
let mut caller = tempfile::NamedTempFile::new().expect("failed to create tempfile");
caller
.write_all(
generate_bin_linking_module(
project.package_dir(),
&format!("{:?}", path.to_string_lossy()),
)
.as_bytes(),
)
.expect("failed to write to tempfile");

let status = Command::new("lune")
.arg("run")
.arg(path)
.arg(caller.path())
.arg("--")
.args(&self.args)
.current_dir(project.package_dir())
.current_dir(current_dir().expect("failed to get current directory"))
.status()
.expect("failed to run script");

drop(caller);

std::process::exit(status.code().unwrap_or(1))
};

Expand Down
2 changes: 1 addition & 1 deletion src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub mod auth;
pub mod commands;
pub mod config;
pub mod files;
pub mod scripts;
pub mod repos;
pub mod version;

pub const HOME_DIR: &str = concat!(".", env!("CARGO_PKG_NAME"));
Expand Down
114 changes: 114 additions & 0 deletions src/cli/repos.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
use crate::{
cli::{config::read_config, home_dir},
util::authenticate_conn,
};
use anyhow::Context;
use gix::remote::Direction;
use pesde::Project;
use std::path::Path;

fn update_repo<P: AsRef<Path>>(
name: &str,
path: P,
url: gix::Url,
project: &Project,
) -> anyhow::Result<()> {
let path = path.as_ref();
if path.exists() {
let repo = gix::open(path).context(format!("failed to open {name} repository"))?;

let remote = repo
.find_default_remote(Direction::Fetch)
.context(format!("missing default remote of {name} repository"))?
.context(format!(
"failed to find default remote of {name} repository"
))?;

let mut connection = remote.connect(Direction::Fetch).context(format!(
"failed to connect to default remote of {name} repository"
))?;

authenticate_conn(&mut connection, project.auth_config());

let results = connection
.prepare_fetch(gix::progress::Discard, Default::default())
.context(format!("failed to prepare {name} repository fetch"))?
.receive(gix::progress::Discard, &false.into())
.context(format!("failed to receive new {name} repository contents"))?;

let remote_ref = results
.ref_map
.remote_refs
.first()
.context(format!("failed to get remote refs of {name} repository"))?;

let unpacked = remote_ref.unpack();
let oid = unpacked
.1
.or(unpacked.2)
.context("couldn't find oid in remote ref")?;

let tree = repo
.find_object(oid)
.context(format!("failed to find {name} repository tree"))?
.peel_to_tree()
.context(format!("failed to peel {name} repository object to tree"))?;

let mut index = gix::index::File::from_state(
gix::index::State::from_tree(&tree.id, &repo.objects, Default::default()).context(
format!("failed to create index state from {name} repository tree"),
)?,
repo.index_path(),
);

let opts = gix::worktree::state::checkout::Options {
overwrite_existing: true,
destination_is_initially_empty: false,
..Default::default()
};

gix::worktree::state::checkout(
&mut index,
repo.work_dir().context(format!("{name} repo is bare"))?,
repo.objects
.clone()
.into_arc()
.context("failed to clone objects")?,
&gix::progress::Discard,
&gix::progress::Discard,
&false.into(),
opts,
)
.context(format!("failed to checkout {name} repository"))?;

index
.write(gix::index::write::Options::default())
.context("failed to write index")?;
} else {
std::fs::create_dir_all(path).context(format!("failed to create {name} directory"))?;

gix::prepare_clone(url, path)
.context(format!("failed to prepare {name} repository clone"))?
.fetch_then_checkout(gix::progress::Discard, &false.into())
.context(format!("failed to fetch and checkout {name} repository"))?
.0
.main_worktree(gix::progress::Discard, &false.into())
.context(format!("failed to set {name} repository as main worktree"))?;
};

Ok(())
}

pub fn update_repo_dependencies(project: &Project) -> anyhow::Result<()> {
let home_dir = home_dir()?;
let config = read_config()?;

update_repo(
"scripts",
home_dir.join("scripts"),
config.scripts_repo,
project,
)?;

Ok(())
}
94 changes: 0 additions & 94 deletions src/cli/scripts.rs

This file was deleted.

8 changes: 6 additions & 2 deletions src/linking/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,12 @@ pub fn get_lib_require_path(
}

/// Generate a linking module for a binary
pub fn generate_bin_linking_module(path: &str) -> String {
format!("return require({path})")
pub fn generate_bin_linking_module<P: AsRef<Path>>(package_root: P, require_path: &str) -> String {
format!(
r#"_G.PESDE_ROOT = {:?}
return require({require_path})"#,
package_root.as_ref().to_string_lossy()
)
}

/// Get the require path for a binary
Expand Down
Loading

0 comments on commit d321b8b

Please sign in to comment.