Skip to content

Commit

Permalink
chore: improve cred callback (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn authored Jan 26, 2024
1 parent 9c07e89 commit c141038
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 37 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ crate-type = ["cdylib"]
chrono = "0.4"
git2 = { git = "https://github.com/rust-lang/git2-rs.git", rev = "502099a", version = "0.18", features = ["default", "vendored-libgit2", "vendored-openssl"] }
libgit2-sys = { git = "https://github.com/rust-lang/git2-rs.git", rev = "502099a", features = ["ssh", "https", "ssh_key_from_memory", "vendored", "vendored-openssl"] }
home = "0.5"
once_cell = "1"

[dependencies.napi]
Expand Down
18 changes: 9 additions & 9 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,15 @@ export interface CredInfo {
url: string
username: string
}
export interface Progress {
totalObjects: number
indexedObjects: number
receivedObjects: number
localObjects: number
totalDeltas: number
indexedDeltas: number
receivedBytes: number
}
/** Check whether a cred_type contains another credential type. */
export function credTypeContains(credType: CredentialType, another: CredentialType): boolean
export const enum RepositoryState {
Expand Down Expand Up @@ -645,15 +654,6 @@ export class FetchOptions {
/** Set extra headers for this fetch operation. */
customHeaders(headers: Array<string>): this
}
export class Progress {
totalObjects: number
indexedObjects: number
receivedObjects: number
localObjects: number
totalDeltas: number
indexedDeltas: number
receivedBytes: number
}
export class ProxyOptions {
constructor()
/**
Expand Down
3 changes: 1 addition & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`)
}

const { Commit, DiffFlags, FileMode, Deltas, DiffDelta, Delta, DiffFile, Diff, ObjectType, GitObject, Reference, ReferenceType, Direction, FetchPrune, AutotagOption, RemoteRedirect, CredentialType, Remote, RemoteCallbacks, FetchOptions, Progress, ProxyOptions, Cred, credTypeContains, RepositoryState, RepositoryOpenFlags, Repository, RepoBuilder, CloneLocal, Sort, RevWalk, Signature, Tree, TreeIter, TreeEntry } = nativeBinding
const { Commit, DiffFlags, FileMode, Deltas, DiffDelta, Delta, DiffFile, Diff, ObjectType, GitObject, Reference, ReferenceType, Direction, FetchPrune, AutotagOption, RemoteRedirect, CredentialType, Remote, RemoteCallbacks, FetchOptions, ProxyOptions, Cred, credTypeContains, RepositoryState, RepositoryOpenFlags, Repository, RepoBuilder, CloneLocal, Sort, RevWalk, Signature, Tree, TreeIter, TreeEntry } = nativeBinding

module.exports.Commit = Commit
module.exports.DiffFlags = DiffFlags
Expand All @@ -317,7 +317,6 @@ module.exports.CredentialType = CredentialType
module.exports.Remote = Remote
module.exports.RemoteCallbacks = RemoteCallbacks
module.exports.FetchOptions = FetchOptions
module.exports.Progress = Progress
module.exports.ProxyOptions = ProxyOptions
module.exports.Cred = Cred
module.exports.credTypeContains = credTypeContains
Expand Down
49 changes: 23 additions & 26 deletions src/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use git2::{ErrorClass, ErrorCode};
use napi::{
bindgen_prelude::*,
threadsafe_function::{ErrorStrategy, ThreadsafeFunction, ThreadsafeFunctionCallMode},
Error, NapiRaw, NapiValue, Status,
Error, NapiRaw, Status,
};
use napi_derive::napi;

Expand Down Expand Up @@ -269,20 +269,24 @@ impl Remote {
) -> Result<()> {
let mut options = git2::FetchOptions::default();
let mut cbs = git2::RemoteCallbacks::default();
cbs.credentials(|url, username_from_url, cred_type| {
cbs.credentials(|url, username_from_url, _: git2::CredentialType| {
if url.starts_with("http") || url.starts_with("https") {
return git2::Cred::default();
}
let user = username_from_url.unwrap_or("git");
if cred_type.contains(git2::CredentialType::USERNAME) {
return git2::Cred::username(user);
}

if let Ok(key) = std::env::var("GPM_SSH_KEY") {
git2::Cred::ssh_key(user, None, std::path::Path::new(&key), None)
return git2::Cred::ssh_key(user, None, std::path::Path::new(&key), None);
} else {
git2::Cred::default()
if let Some(ssh_private_key) =
home::home_dir().map(|h| Path::new(&h).join(".ssh").join("id_rsa"))
{
if ssh_private_key.exists() {
return git2::Cred::ssh_key(user, None, &ssh_private_key, None);
}
}
}
git2::Cred::default()
});
if let Some(callback) = fetch_callback {
cbs.transfer_progress(move |progress| {
Expand Down Expand Up @@ -341,29 +345,22 @@ impl RemoteCallbacks {
/// .fetchOptions(fetchOptions)
/// .clone("git@github.com:rust-lang/git2-rs.git", "git2-rs")
/// ```
pub fn credentials(&mut self, env: Env, callback: JsFunction) -> Result<&Self> {
let func_ref = env.create_reference(callback)?;
pub fn credentials(
&mut self,
env: Env,
callback: Function<CredInfo, ClassInstance<Cred>>,
) -> Result<&Self> {
let func_ref = callback.create_ref()?;
self
.inner
.credentials(move |url: &str, username_from_url, cred| {
env
.get_reference_value::<JsFunction>(&func_ref)
func_ref
.borrow_back(&env)
.and_then(|callback| {
unsafe {
ToNapiValue::to_napi_value(
env.raw(),
CredInfo {
cred_type: cred.into(),
url: url.to_string(),
username: username_from_url.unwrap_or("git").to_string(),
},
)
}
.and_then(|obj| {
callback.call::<Unknown>(
None,
&[unsafe { Unknown::from_raw_unchecked(env.raw(), obj) }],
)
callback.call(CredInfo {
cred_type: cred.into(),
url: url.to_string(),
username: username_from_url.unwrap_or("git").to_string(),
})
})
.map_err(|err| {
Expand Down

0 comments on commit c141038

Please sign in to comment.