Error while cloning repo with nodegit - libgit2

I'm trying to clone a repo with nodegit, but I end up with cloning nothing but .git directory. None of the my other files are being downloaded. And I got this error in the console:
Assertion failed: (t->cred), function on_headers_complete, file ../vendor/libgit2/src/transports/http.c, line 380.
Abort trap: 6
The code I wrote to clone the repo is the following:
Git.Clone(this.options.remoteUrl, this.options.localDir, this.cloneOptions)
.then((repo) => {
if (repo instanceof Git.Repository) {
console.log('Cloned');
repo.checkoutRef('refs/head/master').then((reference) => {
console.log('Checkout master completed');
this.alreadyCloned = true;
this.busy = false;
cb(null, {});
});
} else {
console.error('Failed to clone the repo');
}
})
.catch((err) => {
console.error(err);
this.busy = false;
cb(err);
});
And the clone options:
this.cloneOptions = {
fetchOpts: {
callbacks: {
certificateCheck() {
return 1;
},
credentials() {
return Git.sshKeyMemoryNew(
options.username,
options.publickey,
options.privatekey,
options.passphrase,
);
},
},
},
};
Node version: v8.5.0
OS: MacOS High Sierra (edited)
Besides:
options.publickey, // /Users/safa/.ssh/id_rsa.pub
options.privatekey, // /Users/safa/.ssh/id_rsa
Thanks in advance!

Related

How to implement the Music Metadata Or Music MetaData Browser npm plugin in Cypress V10?

I tried to implement the Node plugin in Cypress Version 10, But I couldn't done it.
https://www.npmjs.com/package/music-metadata-browser#fetchurl-function
Installation is done:
npm install --save-dev music-metadata-browser
npm install --save-dev util
Added the below lines in plugin/index.js
const musicMetadata = require('music-metadata-browser');
const util = require('util');
module.exports = (on, config) => {
require('#cypress/code-coverage/task')(on, config);
on('task', {
validateAudioFormat(audioTrackUrl) {
return new Promise((resolve, reject) => {
musicMetadata.parseFile(audioTrackUrl, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
},
});
};
Added the below code in e2e/validateFile.cy.js
describe('Parsing File', () => {
it('Validating Audio File', () => {
const audioURL = 'cypress/fixtures/media/Patrikios.mp3';
console.log('url: ' + audioURL);
cy.task('validateAudioFormat', audioURL).then(data => {
const allData = Object.values(data);
console.log('All data: ' + allData);
});
/******
cy.on('validateAudioFormat', (url) => {
async () => {
const metadata = await mm.fetchFromUrl(url);
console.log('url: ' + url);
console.log(util.inspect(metadata, { showHidden: false, depth: null }));
};
});
*****/
});
});
Error:
CypressError: `cy.task('validateAudioFormat')` failed with the following error:
The task 'validateAudioFormat' was not handled in the setupNodeEvents method. The following tasks are registered: resetCoverage, combineCoverage, coverageReport
Fix this in your setupNodeEvents method here: /opt/lampp/htdocs/project/cypress.config.js
Commented block error:
taskreadAudioFiles, cypress/fixtures/media/audios/valid/Beyond_Patrick_Patrikios.mp3
CypressError
cy.task('readAudioFiles') timed out after waiting 60000ms
Anyone can help on this scenario?
Thanks!
Your project is a mixture of Cypress v9 config and Cypress v10 tests.
I presume you are on 10+ so the plugins now go in cypress.config.js
const { defineConfig } = require('cypress')
const musicMetadata = require('music-metadata-browser');
const util = require('util');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
require('#cypress/code-coverage/task')(on, config);
on('task', {
validateAudioFormat(audioTrackUrl) {
return new Promise((resolve, reject) => {
musicMetadata.parseFile(audioTrackUrl, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
},
});
},
}
})

Why is Jest running the typescript test files and then the compiled JS test files?

When I run Jest, I get 9 failing, 11 passing out of a total of 20, but there are only 10 tests between two different test files, here it is:
const fs = require('fs');
const assert = require('assert');
import * as jwt from 'jsonwebtoken';
import * as auth from '../services/authentication-service';
const JWT_ERROR_INVALID_SIG = 'invalid signature';
describe('MMD Integration', () => {
const SERVICE = "knox";
const SERVICE_ID = "aluna1";
const badPublicKeyFile = "badkey.pub";
describe('Service Config is accessible', () => {
it('should contain data', async (done) => {
let config: {} | null = null;
config = await auth.getServiceConfig().catch(err => {
console.log("caught getServiceConfig error:", err);
return null;
});
if (config != null) {
assert.include(Object.keys(config), SERVICE);
} else {
console.log("Test failed!");
}
});
});
describe('Public Key', () => {
describe('is valid', () => {
it('should decode successfully', async (done) => {
let config: {} | null = null;
config = await auth.getServiceConfig().catch(err => {
console.log("caught getServiceConfig error:", err);
return null;
});
let publicKey: string | null = null;
if (config) {
publicKey = await auth.getServicePublicKey(SERVICE, config).catch(err => {
console.log("caught getServicePublicKey error:", err);
return null;
});
const token = await auth.genJwt(SERVICE);
if (token == null) {
console.log("genJwt returned null: stopping test");
done();
} else if (!publicKey) {
console.log("No public key: stopping test");
done();
} else {
jwt.verify(token, publicKey, (err, decoded) => {
if (err) {
console.log("WARNING: valid public key failed!", err.message);
} else if (decoded && Object.keys(decoded).includes('vendor')) {
assert.include(Object.values(decoded), SERVICE);
} else {
console.log("Test failed!");
}
});
}
}
});
});
describe('is bad', () => {
const badPublicKey = fs.readFileSync(badPublicKeyFile);
it('should fail verify', async (done) => {
const token = await auth.genJwt(SERVICE);
if (token == null) {
console.log("genJwt returned null: stopping test");
done();
} else {
jwt.verify(token, badPublicKey, (err: any, decoded: any) => {
if (err) {
assert.equal(err.message, JWT_ERROR_INVALID_SIG);
} else {
console.log("WARNING: bad public key worked!", decoded);
}
});
}
});
});
});
describe('Verify Service', () => {
describe('with valid public key', () => {
it('should succeed', async (done) => {
try {
const token = await auth.genJwt(SERVICE);
if (token == null) {
console.log("genJwt returned null: stopping test");
done();
} else {
const result = await auth.verifyService(SERVICE, token).catch(err => {
console.log("caught verifyService error: stopping test", err);
throw new Error(err);
});
assert.equal(result, "OK");
}
} catch (err) {
assert.equal(err, "OK");
}
});
});
describe('with mismatch token', () => {
it('should fail', async (done) => {
try {
const result = await auth.verifyService(SERVICE, "xyz").catch(err => {
console.log("caught verifyService error: stopping test", err);
done();
});
} catch (err) {
assert.notEqual(err, "OK");
}
});
});
});
describe('Service as real MMD', () => {
it('should fail', async (done) => {
try {
const token = await auth.genJwt("mmd");
if (token == null) {
console.log("genJwt returned null: stopping test");
throw new Error('null token');
} else {
const result = await auth.verifyService("mmd", token).catch(err => {
console.log("caught verifyService error:", err);
throw new Error(err);
});
}
} catch (err) {
assert.notEqual(err, "OK");
console.log(err);
}
});
});
});
describe('Get Token from Request Header', () => {
const someToken = "fake-jwt";
const headers = {
'Content-Type': 'application/json'
, 'Authorization': 'Bearer ' + someToken
, 'Aluna-Service': 'foobar'
};
const badHeaders2 = {
'Content-Type': 'application/json'
, 'Authorization': someToken
, 'Aluna-Service': 'foobar'
};
describe('Request header has authorization', () => {
it('should return token', () => {
const result = auth.getTokenFromAuth(headers.Authorization);
assert.equal(result, someToken);
});
});
describe('Request header is missing authorization', () => {
it('should return null', () => {
const result = auth.getTokenFromAuth('');
assert.equal(result, null);
});
});
describe('Authorization is missing Bearer', () => {
it('should return null', () => {
const result = auth.getTokenFromAuth(badHeaders2.Authorization);
assert.equal(result, null);
});
});
});
import request from 'supertest';
import { app } from '../app';
it('renders a greeting to screen', () => {
return request(app).get('/').send({ greeting: 'howdy' }).expect(200);
})
This is what I see in the terminal:
Test Suites: 3 failed, 1 passed, 4 totaload:flatten Completed in 1ms
Tests: 9 failed, 11 passed, 20 total
Snapshots: 0 total
Time: 31.358 s
Ran all test suites.
Watch Usage
› Press f to run only failed tests.
› Press o to only run tests related to changed files.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press q to quit watch mode.
› Press Enter to trigger a test run.
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at Object.getCodec (node_modules/iconv-lite/lib/index.js:65:27)
at Object.getDecoder (node_modules/iconv-lite/lib/index.js:127:23)
at getDecoder (node_modules/raw-body/index.js:45:18)
at readStream (node_modules/raw-body/index.js:180:15)
at getRawBody (node_modules/raw-body/index.js:108:12)
[2022-03-07T18:40:25.852Z] 1.0.1-dev error: uncaughtException: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Error: Caught error after test environment was torn down
This API was meant to work with Jest or that was the original testing suite installed, but someone else came behind and started using Mocha that they are using globally on their machine. Would anyone mind also sharing why tests would pass on their global install of Mocha but not on Jest?
Just wanted to post a solution which is not buried in comments.
By default jest will find any test files in your entire project. If you are building or copying files to a build/release directory, you need to do one of the following:
(Recommended) Exclude the test files from your build pipeline. I usually create a separate tsconfig for building which excludes the test files. Your build command should point to this tsconfig: tsc --project tsconfig.build.json. Note: you can extend tsconfigs so that you don't have to manage duplicates. Here's an example of what your tsconfig.build.json might look like:
{
"extends": "./tsconfig.json",
"exclude": ["src/**/*.test.ts"]
}
-- OR --
Exclude your build directories from jest, adding testPathIgnorePatterns: ['dist/'] to your jest.config.js (assuming your compiled JavaScript files are in the dist folder)

React-Native 62.2 code image upload Error : network error

I am using React-Native two days back After React-Native version upgrading to 0-62.2, I encountered many problems.
Among them important one is image upload error getting [Error:Network error ]
Before upgrading the React-native my code is working fine
Below code is working fine for me for multiple image upload before upgrading to React-Native 0.62.2 but now i am getting [Error: Network error]
constructor() {
super();
this.state = {
uploadPercentage: 0,
}
}
// upload Files upload_Files = async () => {
upload_File() {
if (this.validate_Fields()) {
const { image, images, files, description, userId, size } = this.state;
console.log('AddPost Screen : upload_File:', 'userId:', userId, 'Files:', files, 'description:', description)
// this.setState({ error: '', loading: true });
if (this.state.type === 'image/jpeg') {
console.log('AddPost Screen : upload_ files :', files);
const formData = new FormData();
formData.append('user_id', userId);
formData.append('description', description);
// formData.append('files[]', files);
for (let i = 0; i < files.length; i++) {
formData.append('files[]', {
name: files[i].path.split('/').pop(),
type: files[i].mime,
uri: Platform.OS === 'android' ? files[i].path : files[i].path.replace('file://', ''),
});
}
// upload percentage progress bar ******************************************************
const options = {
onUploadProgress: (progressEvent) => {
const { loaded, total } = progressEvent;
let percent = Math.floor((loaded * 100) / total)
console.log(`${loaded}kb of ${total}kb | ${percent}%`);
if (percent < 100) {
this.setState({ uploadPercentage: percent })
}
}
}
axios.post(API_URL + '/fileuploadapi/uploadPost', formData, options, {
headers: { "Content-type": "multipart/form-data" }
}).then((response) => {
console.log(JSON.parse(JSON.stringify(response.status)));
// upload percentage progress
this.setState({ uploadPercentage: 100 }, () => {
setTimeout(() => {
this.setState({ uploadPercentage: 0 })
}, 1000);
})
this.cleanupImages();
Alert.alert('Upload Post Successfully');
}).catch((error) => {
console.log(error);
this.cleanupImages();
Alert.alert('image Upload Post Failed , Try again !');
});
}
}
}
// clear files data
cleanupImages() {
this.setState({
description: '',
image: null,
images: null,
// video: '',
files: '',
uploadPercentage: 0,
})
ImagePicker.clean().then(() => {
console.log('removed tmp images from tmp directory');
}).catch(error => {
alert(error);
});
}
If anyone know the solution please let me know ...
I just found the solution for the React-Native 62.2 upgrading error for image upload Error
[Error: network error]
Just remove the file "ReactNativeFlipper.java" from debug/java folder
File Location :
android/app/src/debug/java/com/appname/ReactNativeFlipper.java

Gulp 4 keep watching even on error

How can I make this
// ...
gulp.watch(source.app, gulp.series(
lint(source.app),
transpile(source.app),
ATDD,
));
To keep watching even if error occurred from linter or transpiler?
My task function looks like this:
// ...
function lintWorker(source) {
return gulp.src(source)
.pipe(tslint({
configuration: "tslint.json",
options : {
formatter: "prose"
}
}))
.pipe(tslint.report(stylish, {
emitError: false,
sort: true,
bell: true
}));
};
export function lint(source) {
let fn = () => {
return lintWorker(source);
};
fn.displayName = ["linting", ...source].join(" ");
return fn;
};
I found the simple way how to do it.
gulp.watch(source.app, (done) => {
gulp.series(
lint(source.app),
transpile(source.app),
ATDD,
)((err) => {
if (err) {
console.error("error", err);
}
done();
});
});

No error shown in console when thrown from inside hapi plugin

For some reason no error shows up in the server console when I start my hapi server with nodemon and navigate to http://localhost:3000/hapi-ext-fetch and this makes debugging very difficult. Here is my code:
var Hapi = require('hapi');
var Joi = require('joi');
var fetch = require('isomorphic-fetch');
var debugMode = { debug: { request: [ 'error', 'request-internal' ] }};
var server = new Hapi.Server(debugMode);
server.connection({ port: 3000 });
var myPlugin = {
register: function (server, options, next) {
server.route([
{
method: 'GET',
path: '/{name}',
handler: function ( request, reply ) {
throw new Error('this error isnt shown!');
},
config: {
validate: {
params: {
name: Joi.string().min(3).max(10)
}
}
}
}
]);
next();
}
};
myPlugin.register.attributes = {
name: 'myPlugin',
version: '1.0.0'
};
server.register([
{
register: myPlugin,
routes: {
prefix: '/test'
}
}
], function() {
server.ext( 'onPreResponse', ( request, reply ) => {
if ( typeof request.response.statusCode !== 'undefined' ) {
return reply.continue();
}
fetch('http://localhost:3000/test/whatever')
.then(function(result) {
reply(result);
})
.catch(function(err) {
reply('error on server side: ' + err.stack);
});
});
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
});
I'm using hapi 13.0.0
Can't say I totally understand your use case here and if this question will be helpful to other people. But what you're trying to do it seems is:
Send a request to /hapi-fetch-ext
Have that request 404
And then in an onPreResponse go fetch another route /test/whatever
Hope to see the "this error isn't shown error"
Not sure if you're aware but this is going to cause an infinite cycle of requests (your fetch will cause another onPreResponse and so on and so on). So you should probably only go fetch on a 404:
server.ext( 'onPreResponse', ( request, reply ) => {
if (request.response.isBoom && request.response.output.statusCode === 404) {
return fetch('http://localhost:3000/test/whatever')
.then(function(result) {
reply(result);
})
.catch(function(err) {
reply('error on server side: ' + err.stack);
});
}
return reply.continue();
});