Yeoman using NodeGit's Reset, getting constant object error - node.js

First time using NodeGit and having issues with the Reset function.
I'm trying to reset a folder that has been cloned to the current HEAD of origin/master.
Even though i'm giving it a target, it says it's still required:
Error: Object target is required.
Current code:
var Reset = nodegit.Reset;
var templateDir = this.templatePath('/folder');
nodegit.Repository.open(templateDir)
.then(function(repo) {
repository = repo;
Reset.reset(repository, templateDir, Reset.TYPE.HARD, {
remoteCallbacks: {
credentials: function(url, userName) {
return nodegit.Cred.sshKeyNew(userName, sshPublicKey, sshPrivateKey, "");
}
}
})
.done(function(repo) {
console.log("reset done");
});
});
templateDir is the full path to the folder using Yeoman's templatePath.
Wondering if anyone can give me insight into what i'm doing wrong or missing. I didn't see an example for this in their Example folder.
My expected end result would be equal to running this in terminal:
git reset --hard origin/master

You can check the test case that does a hard reset for an example.
The gist is that templateDir is the commit object that you want to reset to. You don't really need remoteCallbacks either unless you want to do a fetch or some sort of remote operation.
Try this:
var Reset = nodegit.Reset;
var templateDir = this.templatePath('/folder');
var repository = repo;
nodegit.Repository.open(templateDir)
.then(function(repo) {
repository = repo;
return repository.fetch('origin');
})
.then(function() {
return repository.getBranchCommit('origin/HEAD');
})
.then(function(originHeadCommit) {
return Reset.reset(repository, originHeadCommit, Reset.TYPE.HARD);
})
.done(function(repo) {
console.log("reset done");
});

Related

Git diff gives no output although SHA for image is different

I'm trying to create a deployment script which will let me know whether or not I have the latest image of my project deployed on either my master or development branch.
I'm attempting to use git.diff to compare the SHA1 hash of the deployed image against my local repository, and although the hashes are clearly different, git.diff gives me no output. I don't understand what's going on here, since if the SHA1 is different, there must surely be changes to show from git.diff?
This is the code I have written so far:
#!/usr/bin/node
// get an exec function from node we can use to run shell commands
const exec = require('util').promisify(require('child_process').exec);
// check the user supplied the folder name of the repo as an arg
if (!process.argv[2]) {
console.error('argument missing');
process.exit(1);
}
// initialize our git client using the repo path arg
const git = require('simple-git/promise')("../../" + process.argv[2]);
var projectNameArray = process.argv[2].split(".");
const projectName = projectNameArray[0] + "-" + projectNameArray[1] + "-" + projectNameArray[2]
console.log('\x1b[36m%s\x1b[0m', 'Your project name is:', projectName);
// use an IIAFE for async/await
(async () => {
// run git rev-parse development and
var devSha1 = await git.revparse(['development']);
console.log('\x1b[36m%s\x1b[0m', 'devSha1: ', devSha1);
devSha1 = devSha1.replace(/(\n)/gm,"");
// run git rev-parse master
var masterSha1 = await git.revparse(['master']);
console.log('\x1b[36m%s\x1b[0m', 'masterSha1: ', masterSha1);
masterSha1 = masterSha1.replace(/(\n)/gm,"");
// use kubectl to export pods to JSON and then parse it
const { stdout, stderr } = await exec(`kubectl get deployment ${projectName} -o json`);
const pods = JSON.parse(stdout);
const imageName = pods.spec.template.spec.containers[0].image;
//get deployed image has
const commitHashArray = imageName.split('development-' || 'master-');
console.log('\x1b[36m%s\x1b[0m', 'Deployed image: ', commitHashArray[1]);
var diffArray = new Array(devSha1, commitHashArray[1])
//logic to tell if latest is deployed of if behind
if (commitHashArray[1] == devSha1){
console.log('\x1b[32m%s\x1b[0m', 'You have the latest image deployed');
} else {
console.log('\x1b[31m%s\x1b[0m', 'You don\'t have the latest image deployed');
await git.diff(diffArray);
}
})().then(() => console.log('\x1b[32m%s\x1b[0m', 'Ok')).catch((e) => console.error(e));
This gives me the following console output:
Your project name is: xxx-xxx-xxx
devSha1: 6a7ee89dbefc4508b03d863e5c1f5dd9dce579b4
masterSha1: 4529244ba95e1b043b691c5ef1dc484c7d67dbe2
Deployed image: 446c4ba124f7a12c8a4c91ca8eedde4c3c8652fd
You don't have the latest image deployed
Ok
I'm not sure if I'm fundamentally misunderstanding how git.diff works, or if something else is at play here. The images clearly don't match, so I would love if anyone could explain why there is no output from this function?
Thanks! :)

exceljs node.js write file does not work on VPS but works on Localhost

When I am trying to save excel file created with this repo: https://github.com/guyonroche/exceljs#create-a-workbook
on a localhost it works, the file is got created and available to open and read and edit.
But when doing the same thing on my VPS the .then function and the .catch function just return nothing.
The file is actually created in the server but I got the next error when trying to open it:
The file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
This is the code:
app.get("/excel/createDemoExcel", function(req, res, next) {
var workbook = new Excel.Workbook();
workbook.creator = 'mydomain.com';
workbook.lastModifiedBy = 'The name of the Team';
workbook.created = new Date();
workbook.modified = new Date();
workbook.rightToLeft = true;
let sheetParams = {
views:[
{
xSplit: 1, ySplit:1
}
],
pageSetup: {
paperSize: 9,
orientation:'landscape'
},
views: [
{
rightToLeft: true
}
]
};
workbook.addWorksheet('mySheet', sheetParams);
let mySheet = workbook.getWorksheet('mySheet');
mySheet.columns = [
{
width:20,
},
{
width:20
},
{
width:30
}
];
mySheet.addRow(["Raz", "Buchnik", "0509921014"]);
mySheet.addRow(["Amos", "Fadlon", "0508555550"]);
mySheet.addRow(["Dgani", "Lavi", "0501231231"]);
mySheet.getRow(1).font = {
size: 16,
bold: true,
};
mySheet.getCell("A5").value = "Yes";
mySheet.getCell("C5").value = "Yes1";
mySheet.mergeCells("A5:C5");
console.log("Trying to export");
workbook.xlsx.writeFile("src/excelUploads/mySheet.xlsx")
.then(function() {
console.log("Exported");
res.end("Excel");
}).catch(function(err) {
console.log("Errored");
});
});
Maybe someone familier with?
Ive tried to set the directory 777 but still not working.
Thanks!
A bit annoying that they don't make this clear, but there is a separate module for some file types. According to the GitHub README.md, you can install this extension. They provide an installer script, so just:
curl https://raw.githubusercontent.com/guyonoche/exceljs-formats/master/install.sh -L | sudo bash
Hopefully this helps. I was really confused with this error myself.
You might want to downgrade your version of Exceljs. See this topic: https://github.com/exceljs/exceljs/issues/883
I also had the issue that it worked fine locally, but not on the server. Downgraded the package to 1.10.0 and everything works also on the server now.

Nodejs Error: spawn git ENOENT when using simple-git to clone repo

I am building an app that clones a repo, parses xml files in the repo and displays the information. I am using the simple-git npm module. I have this working on my local system, and on the dev test server. I am trying to deploy it to an integration server and this is the error I get. Some of the stuff I have seen says it is because the directory I'm attempting to clone to doesn't exist, but it most definitely does.
Here is the code I wrote to either clone the repo if it doesn't exists or pull pull the latest changes. This is a method of a class. this.path is the path to the directory the repo will be cloned to. this.repoRoot is the path to the root of the repo on the local system. this.remote is the url for the remote.
/**
* gets the latest version of the remote repo and specified branch by either using clone or pull
* #return {Promise<void>}
*/
getLatest() {
return new Promise((resolve, reject) => {
this.checkForDir(this.path).then((parentDirExists) => {
if (!parentDirExists) {
fs.mkdirSync(this.path);
}
}).then(() => {
this.checkForDir(this.repoRoot).then((repoExistsLocally) => {
if (!repoExistsLocally) {
git(this.path).clone(this.remote).then((cloneResult) => {
git(this.repoRoot).checkout(this.branch).then(() => {
resolve();
});
});
}
else {
git(this.repoRoot).pull().then((pullResult) => {
resolve();
});
}
})
})
})
}
Thanks in advance for any help!
As it turns out, the problem was related to permissions the account the server was running on. The account did not have permissions to write to the directory it was attempting to write to.

module is not defined error

I am using nodejs in my meteor app and I added packages using mrt add npm and then in my client directory in packages.json I added skimlinksjs and its version and it is added to my app.
When I tried to using them in my app in server side code like this,
var res;
var skim = Meteor.require('skimlinksjs');
var apili = Meteor.require('/config.js');
skim.setup(apili.key);
skim.query({
searchFor: "title:\"moto g\"",
fq: "country:US"
}, function(err,data) {
res=data.skimlinksProductAPI.numFound;
}
);
return res;
and my config.js file is like this
module.exports = {
key: "xxxxxxx"
}
whenI'm running this application it is showing error like
module not defined
What went wrong with my code or is there any need to install other packages?
I just got the answer
Write this function in server side code
function returnAllResult()
{
var skimlinks = Meteor.require('skimlinksjs');
skimlinks.setup("xxx");
var skimlinks_query = Async.wrap(skimlinks.query);
var result = skimlinks_query({
searchFor: "title:\"moto g\"",
fq: "country:US",
rows:5
});
return result;
}
to know about asynchronous functions watch this
and then in my server side methods call this
apiresult:function()
{
var response = returnAllResult();
return response.skimlinksProductAPI.products[0].merchant;
}
that's it working fine now. Hope this helps someone

How to access multiple models from a controller

I have a Locations model and a Recorders model. I want to be able to pass all of the data for both data sets to my view model. How can I access them though because I think they're not in scope since I'm getting undefined errors because I'm calling 'all'
https://gist.github.com/3998302
var Main = function () {
this.index = function (req, resp, params) {
var self = this;
var data = {};
geddy.model.Locations.all(function(err, locations) {
data.locations = locations;
geddy.model.Recorders.all(function(err, recorders) {
data.recorders = recorders;
self.respond({params: params, data: data}, {
format: 'html'
, template: 'app/views/locations/index'
}
});
}););
};
};
exports.Main = Main;
Error snippet:
timers.js:103
if (!process.listeners('uncaughtException').length) throw e;
^
TypeError: Cannot call method 'all' of undefined
at index (G:\code\PeopleTracker\app\controllers\main.js:23:24)
at controller.BaseController._handleAction.callback (C:\Users\Chris\AppData\Roaming\npm\node_modules\geddy\lib\base_
controller.js:387:22)
So it looks like you're initializing the data variable to 'undefined'. Try data = {} instead. If that doesn't fix it, I'll do some troubleshooting with you.
EDIT
If that doesn't do it for you, try installing geddy again:
npm uninstall -g geddy && npm install -g geddy
If that doesn't do it, make sure that your DB is actually running, make sure that the models are defined (try geddy console to check your models), and make sure that you're on the latest stable version of node.
Very late to the party, but I believe you can just call
geddy.model.Locations.all(function(err, locations) {
geddy.model.Recorders.all(function(err, recorders) {
var data = {};
data.locations = locations;
data.recorders = recorders;
self.respond({params: params, data: data}, {
format: 'html'
, template: 'app/views/locations/index'
}
});
}););
You could also have the respond say
self.respond({params: params, locations: locations, recorders: recorders});
but if you want all of that data available from the data literal you need it defined in the lowest scope callback. The callbacks can read above their scope but they cannot write above it.

Resources