Git diff gives no output although SHA for image is different - node.js

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! :)

Related

How to deploy a solana program from a particular address or public key

I've two problems here, major of all, I can't understand the difference between account address and public key of a program
The second thing is, there is a problem while deploying my solana program. I've made a deployment script...
const { Keypair } = require("#solana/web3.js");
const { Connection, LAMPORTS_PER_SOL } = require("#solana/web3.js");
const path = require('path');
const spawn = require("cross-spawn");
const fs = require('fs');
//import { Connection, LAMPORTS_PER_SOL } from "#solana/web3.js"
async function main(){
const SLASH = path.sep;
let programAuthorityKeypair = new Keypair();
this.connection = new Connection("https://api.devnet.solana.com", "confirmed");
const signature = await this.connection.requestAirdrop(programAuthorityKeypair.publicKey, LAMPORTS_PER_SOL * 5);
await this.connection.confirmTransaction(signature);
const programAuthorityKeyfileName = `target/deploy/programauthority-keypair.json`
const programAuthorityKeypairFile = path.resolve(
`${__dirname}${SLASH}${programAuthorityKeyfileName}`
);
fs.writeFileSync(
programAuthorityKeypairFile,
`[${Buffer.from(programAuthorityKeypair.secretKey.toString())}]`
);
const programKeyfileName = `target/deploy/solblog-keypair.json`
const programKeypairFile = path.resolve(
`${__dirname}${SLASH}${programKeyfileName}`
);
let programKeypair = readKeyfile(programKeypairFile);
let programId = programKeypair.publicKey.toString();
//////////////////////////////////configurations//////////////////////////////////
let method = ["deploy"] // we are deploying for the first time, using 'deploy'
spawn.sync(
"anchor",
[
...method, // we use a variable so we when we want to upgrade, we can use 'upgrade' instead
"--provider.cluster", // we want to specify the node cluster
"Devnet", // the node cluster as the Devnet
"--provider.wallet", // we need to pass in a keyfile to pay for the deployment
`${programAuthorityKeypairFile}`, // this is the keypair file we created just a moment ago
],
{ stdio: "inherit" }
)
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
function readKeyfile(keypairfile) {
let kf = fs.readFileSync(keypairfile)
let parsed = JSON.parse(kf.toString()) // [1,1,2,2,3,4]
kf = new Uint8Array(parsed)
const keypair = Keypair.fromSecretKey(kf)
return keypair
}
now, I'm running the script by node deploy.js but it is giving me balance insufficient error...
Deploying workspace: https://api.devnet.solana.com
Upgrade authority: /home/adil/Desktop/solblog/target/deploy/programauthority-keypair.json
Deploying program "solblog"...
Program path: /home/adil/Desktop/solblog/target/deploy/solblog.so...
===========================================================================
Recover the intermediate account's ephemeral keypair file with
`solana-keygen recover` and the following 12-word seed phrase:
===========================================================================
all orbit slim nothing learn country polar casual print help coffee gesture
===========================================================================
To resume a deploy, pass the recovered keypair as the
[BUFFER_SIGNER] to `solana program deploy` or `solana write-buffer'.
Or to recover the account's lamports, pass it as the
[BUFFER_ACCOUNT_ADDRESS] argument to `solana program close`.
===========================================================================
Error: Account JjetRg5FHM6xpPjTT7KfrEaTBeEWxMh5Pyjo4UXw3nm has insufficient funds for spend (1.8711612 SOL) + fee (0.00135 SOL)
There was a problem deploying: Output { status: ExitStatus(unix_wait_status(256)), stdout: "", stderr: "" }.
so I'm taking the above account address JjetRg5FHM6xpPjTT7KfrEaTBeEWxMh5Pyjo4UXw3nm to solana faucet site, and airdropping 5 SOLs into that address then again I'm running the script, AND GETTING THE SAME ERROR WITH DIFFERENT ACCOUNT like...
Error: Account .
already set the env to the DEVNET.
What I'm thinking that how can I deploy the program with the same account into which I'm airdropping SOLs?

Does the pre-merge commit hook get executed when I click merge request button in github?

I want to update the package version automatically when I create a pull request from release branch to master and after that I want whenever I merge it, the pre-merge git hook will be executed to launch another script.
pre-merge-commit:
cd my_app
node ./hooks/post-commit-version
RETVAL=$?
if [ $RETVAL -ne 0 ]
then
exit 1
fi
hooks/post-commit-version:
#!/usr/bin/env node
const exec = require('child_process').exec;
const path = require('path');
const moment = require('moment');
const fs = require('fs');
function getBranch(){
return new Promise((resolve, reject) =>{
exec(
"git branch | grep '*'",
function (err, stdout, stderr) {
if(err)reject(err)
const name = stdout.replace('* ','').replace('\n','');
resolve(name)
}
)
});
}
getBranch()
.then((branch) => {
if(branch === 'release') {
const currentDate = moment().format('YY.MM.DD')
var pathToFile = path.join(__dirname, "../package.json");
if (fs.existsSync(pathToFile)) {
const data = fs.readFileSync(pathToFile, 'utf-8')
const content = JSON.parse(data);
content.version = currentDate;
fs.writeFileSync(pathToFile, JSON.stringify(content, null, 2), 'utf8');
exec(`git add ${pathToFile}`, (err, stdout, stderr) => {
if(err) console.log(err)
console.log(stdout)
})
} else {
console.log("Cannot find file : " + pathToFile);
return;
}
}
return;
})
.catch(error => {
console.log(error)
})
When I try this locally, with pre-commit hook and execute the git commands manually, it works successfully and update the repository in github as the one I want it to be. But I'm not sure that git hooks are executed in Github server when I click the merge request button.
The short answer is no.
Hooks are tied to one specific repository and are not transferred by Git operations.1 Any hooks you set up in your repository are not set up in some other repository. So the hook you have in your repository acts in and on your repository, but if you have a second clone elsewhere, it does not act in and on that second clone.
Besides this, GitHub use a different mechanism ("GitHub Actions") and just don't let you put any hooks into their repositories in the first place.
1If your OS provides symbolic links, you can (manually, once per clone) install a symlink as a Git hook, with the symlink pointing to a file in the work-tree for your repository. In this way, you can get a hook that is affected by various operations: since the hook's actual executable code lives in your work-tree, things that affect that file in your work-tree affect the hook.
Similarly, on OSes that don't provide symbolic links, you can (manually, once per clone) install a hook script-or-binary that works by running a script-or-binary out of your work-tree. That is, rather than relying on the OS's symbolic link mechanism to run the file directly from your work-tree, you write a hook whose "run" operation consists of "run file from work-tree and use its exit status as the hook's exit status".

How would I write a changed variable to my config.js file for a permanent change?

My Problem
I am currently writing a Discord bot to be used on one server at the moment. I have set up a command that will change the prefix of the bot's commands but as soon as I restart my repl, it resets to the original prefix. I would like to change the command so that it will write to my config.js file to stop this from happening.
What I've Tried So Far
To be honest, I haven't tried anything yet as I have no idea where to start
My code Files
config.js file:
var config={};
config.token = "My Bot Token";
config.prefix = "//";
config.statusMessage = "video games | (" + config.prefix + "help)";
config.dbltoken = undefined;
module.exports = config;
change-prefix.js file:
config = require('../config.js');
module.exports = (client, message, args) => {
config.prefix = args;
message.reply("Prefix has been changed to: " + config.prefix);
console.log("Command Used: Change-Prefix");
}
What Should Happen
The change-prefix.js file should successfully write the new prefix determined by the user to the config.js file. At this moment in time, I have no errors, but I would like to change this as it would vastly improve the user experience for my bot.
If you want to write the file, you can use fs module. The code below saves custom prefix to prefix.txt file and checks if it exists every time you start your repl. If not, it's using the default value.
Note: the code doesn't have any error handling or any other features, it's just a simple code to show you the idea. In real life scenario, you'll probably want to save your prefix to database, add per-server prefix setting, filter messages from other bots, include prefix in command invocation. Just one more thing - please put Discord token in .env, not in config file.
const Discord = require('discord.js');
const fs = require('fs');
const config = require('./config.js');
const client = new Discord.Client();
// If prefix.txt exist, use it. Otherwise, get data from config file
let prefix = fs.existsSync('prefix.txt') ? fs.readFileSync('prefix.txt').toString() : config.prefix;
client.on('message', (msg) => {
// 'set prefix XXX' to change your prefix to XXX
if (/^set prefix /i.exec(msg.content)) {
const newPrefix = msg.content.split(' ')[2];
fs.writeFile("./prefix.txt", newPrefix, function(err) {
if(err) {
return console.log(err);
}
prefix = newPrefix;
console.log(`Prefix changed to ${prefix}`);
});
}
// 'show prefix' to show current prefix
if (/^show prefix/i.exec(msg.content)) {
console.log(`Prefix is ${prefix}`);
};
});
client.on('ready', () => {
console.log(`I'm in`);
});
client.login(process.env.DISCORD_TOKEN);

Teamcity - Env Variables Created using Nodejs step Not available in next step (nodejs/commandline)

I am using nodejs build step to create enviornment variables (on linux agent) using process.env["something"] = "somethingelse". After creation if I echo the variables, i can see the values but as soon as I go in next build step all the env variables created go away. How can I fix this issue? I am using team city 10. I can not use the env variables functioanlity provided as part of parameters so that is why need to go via this route. Any help will be really appreciated. Here is the code written in nodejs teamcity step.
fs = require('fs');
var envFile = process.argv[2];
fs.readFile(envFile , 'utf8', function(err, data) {
if (err) {
return console.log(err);
}
var json = JSON.parse(data);
for (var key in json) {
process.env[key] = json[key];
console.log(process.env[key]);
}
});

Yeoman using NodeGit's Reset, getting constant object error

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");
});

Resources