How to clone a repository with SSH using simple-git?
I'm trying to clone using this code
const git: SimpleGit = simpleGit();
const sshUri = 'git@..........'
const localPath = '/usr/workspace';
git
.clone(
sshUri,
localPath
).then((data) => {
console.log('success');
}).catch((err) => {
console.log(err);
});
But I am getting an exception
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
If your git repo is private, you will need to generate SSH key and add this key to your GIT account.
Code example
private async cloneRepo() {
const gitSSH = 'FILL YOUR SSH GIT ADDRESS';
const sourceDir = path.resolve(`${os.tmpdir()}/${this.projectKey}`);
const sshKnownHosts = path.resolve(`${process.cwd()}/settings/ssh/known_hosts`)
const sshKey = path.resolve(`${process.cwd()}/settings/ssh/id_ed25519`)
const GIT_SSH_COMMAND = `ssh -o UserKnownHostsFile=${sshKnownHosts} -o StrictHostKeyChecking=no -i ${sshKey}`;
console.log(sourceDir);
const git: SimpleGit = simpleGit()
.env('GIT_SSH_COMMAND', GIT_SSH_COMMAND)
.clean(CleanOptions.FORCE);
await git.clone(gitSSH, sourceDir, ['-b', 'YOUR-BRANCH-NAME', '--single-branch'])
.then(() => console.log('finished'))
.catch((err) => console.error('failed: ', err));
}