I want to use a nodejs script to clone and do some other ops at a given repo. However, whenever I do shell.cd(path) as seen below it crashes with the
"No directory name could be guessed"
Here's the script
const nodeCron = require("node-cron");
const shell = require('shelljs');
const path = './';
require('dotenv').config();
const start = Date.now();
async function GitOps(){
console.log("Running scheduled job", start);
shell.cd(path);
shell.exec('git clone -b dev https://',process.env.USERNAME,':',process.env.PASSWORD,'#github.com:Jamesmosley/xyz-git-ops.git');
return console.log("Job finished");
}
const job = nodeCron.schedule("* * * * *", GitOps);
I mean to clone right into my working directory. I tried some stuff like adding 'pwd' at the const path and adding the root folder at the end of the clone command, to no avail:
shell.exec('git clone -b dev https://',process.env.USERNAME,':',process.env.PASSWORD,'#github.com:Jamesmosley/xyz-git-ops.git' ./);
After all, the only thing missing was literaly pasting my absolute path into the path variable:
const path = '/Users/Jamesmosley/Documents/Git Ops Cron/repos';
then doing shell.cd(path)
Related
In cypress how can I ignore the dotenv (.env) file while running in jenkins, as jenkins run on actual environment variables. Now I am getting No such file or directory open/student-proj/.env
How can I check if it is running in jenkins then use actual env variables else use .env ?
plugins/index.js
const configEnv = require('dotenv').config();
const cucumber = require('cypress-cucumber-preprocessor').default;
module.exports = (on, config) => {
on('file:preprocessor', cucumber());
if (configEnv.error) {
throw configEnv.error;
}
const env = { ...config.env, ...configEnv.parsed };
const envData = { ...config, env };
return envData;
}
why not just use a jenkins env variable specific in your code e.g. JOB_NAME ... if the value returns null... that means its not running on jenkins
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! :)
const fs = require("fs")
//const HOW = "/home/test/everything"
// const HOW = "/home/test/"
// This one fails. My home is encrypted and it cannot read directories, it gets the .Private file. I want to read files and directories in my home folder. But can't.
const HOW = "/home/test/folder/"
// This one works for some reason. It lists all the directories in the folder.
// const HOW = "folder"
// This one works as well
var list = walk(HOW)
console.log(list)
// How do I get contents of /home/test (which happens to be my home folder).
// I'm both root and "test" user of the computer.
I'd like to have walk() work on /home/test/.
The code that fails:
var walk = function(dir) {
var results = []
var list = fs.readdirSync(dir)
list.forEach(function(file) {
file = dir + '/' + file
var stat = fs.statSync(file)
if (stat && stat.isDirectory()) results = results.concat(walk(file))
else results.push(file)
})
return results
}
The exact line causing it (stack trace): var stat = fs.statSync(file)
The error is:
Error: ENOENT: no such file or directory, stat '/home/test/.Private/###############################################################'
Where # is an amount of letters whose importance to safety is unknown to me.
Node.js doesn't have a problem addressing any folder contained within my home folder, but cannot address the home folder itself. Neither my own account nor root account can get access to it.
I think you are adding an unnecessary /. Try changing
const HOW = "/home/test/folder/"
to
const HOW = "/home/test/folder"
Here's my pre-commit hook:
#!/bin/sh
exec node build.js
That code works fine when I change pre-commit to pre-commit.sh and run it, it also executes correctly when I just run exec node build.js in the terminal. The build file works fine.
Here's build.js:
var fs = require("fs")
var through2 = require('through2');
var markdownPdf = require("markdown-pdf")
var removeMarkdown = require("remove-markdown")
var resume = fs.createReadStream("README.md")
var pdf = fs.createWriteStream("Resume - Desmond Weindorf.pdf")
var txt = fs.createWriteStream("Resume - Desmond Weindorf.txt")
var md = fs.createWriteStream("Resume - Desmond Weindorf.md")
process.stdout.write('Building other file types...\n')
// pdf
resume.pipe(markdownPdf({ paperBorder: "1.4cm" })).pipe(pdf)
// txt
resume.pipe(through2(function(line, _, next) {
this.push(removeMarkdown(line.toString()) + '\n');
next()
})).pipe(txt)
// md
resume.pipe(md)
I thought it might be ending prematurely (and probably is) before the new files are written to, but the terminal should still display the initial write output in that case.
This was my output on a commit (the pdf was changed beforehand to test if it was overwriting with new changes):
Desmonds-MacBook-Pro:resume desmond$ git commit -am "updated resume"
[master 7faab35] updated resume
4 files changed, 36 insertions(+), 34 deletions(-)
rewrite Resume - Desmond Weindorf.pdf (81%)
What am I doing wrong here?
I am trying to repeatedly update a file using a cronjob. Eventually, this is going to be more complicated but for now I'm trying to figure out my current problem. I know the code below is somewhat over-complicated because I preserved the basic structure while trying to problem solve. Here is the server file:
// server.js
var express = require('express');
var port = process.env.PORT || 8080;
var http = require('http');
var fs = require("fs");
var curtainup = require('./diagnoseleak.js');
var url = require("url" );
var app = express();
// launch ======================================================================
app.listen(port);
//run the CronJob
var CronJob = require('cron').CronJob;
new CronJob('0 * * * * *', function() {
console.log("running");
var date = new Date();
console.log("Ran at: "+date.getHours()+":"+date.getMinutes());
curtainup.doitnow();
} , null, true, 'America/New_York');
And here is the file referenced called diagnoseleak.js:
var fs = require("fs");
var mostRecentLocation = "./config/pullfiles/mostRecent55.txt";
module.exports = {
doitnow: function(){
var writethefile = function(){
fs.writeFileSync(mostRecentLocation, "A file called mostRecent55 should be create with this text", { flag: 'w' });
console.log("This should write to the console");
}
writethefile();
}
}
From the directory that houses the server file, I type the following into cmd:
git add .
git commit -m "adding files"
git push heroku master
heroku run bash
Then into the bash window I type:
cd config/pullfiles
ls -l
AND...no file called mostRecent55.txt appears. Am I looking in the wrong place? Eventually I want to be able to update a file, but I have a feeling I'm either looking in the wrong place for this mostRecet55.txt file or going about the process of writing it incorrectly.
heroku doesn't let you write files onto the filesystem where your app is stored. You would need to use an add-on, database or external service of some kind. The only exception seems to be /tmp which is only temporary storage