How to set a pre-defined dynamic name for a variable in a jenkins declarative pipeline - variables

Is it possible to set a pre-defined dynamic name for a variable in a jenkins declarative pipeline ?
env {
TEST_2_SERIAL = 456789
}
stage('Test') {
steps {
echo ${TEST_${HARDWARE}_SERIAL}
}
}
when ${HARDWARE} value is 2 and ${TEST_2_SERIAL} value is predefined as 456789, then ${TEST_${HARDWARE}_SERIAL} should be 456789

I don't know if it achieves what you expect but it is possible to access the environment variable dynamically in this way.
pipeline {
agent any
environment {
TEST_2_SERIAL = 456789
HARDWARE = '2'
}
stages{
stage('Test') {
steps {
echo env["TEST_${HARDWARE}_SERIAL"]
}
}
}
}
The echo will print out the value of TEST_2_SERIAL.

Related

how to pass date variable to graphQL call in svelte?

I have a graphql file with a date in ISO format. I would like to pass a variable instead of hardcoding the date. I would like to use Date.toISOstring() or some get current date method.
GRAPHQL FILE
let today = Date.toISOString() //or DateNow()
query guide {
tv {
guide(date: "2022-08-10T00:00:00Z <-replace--${today}") {
entries {
channel {
show{
......
}
}
}
}
}
}
Is this possible?
Use a GraphQL variable and pass it to your query. Here are the adjustment you have to make to the query. I am guessing the name of the date scalar here (DateTime), it might as well simply be String. Check the documentation of the API to get the correct name.
query guide($date: DateTime!) {
tv {
guide(date: $date) {
entries {
channel {
show{
......
}
}
}
}
}
}
If you use Svelte Apollo for example, you can pass the variables like this:
const guide = query(GUIDE_QUERY, {
variables: { date: new Date().toIsoString() },
});

Configuration for multi-step parallel stages

I have a mono-repo that contains multiple services. Ideally, I want to test each service in parallel. Each branch has 2 stages:
test
benchmark
To give something similar to this:
clone
/ \
/ \
/ \
/ \
svc1-test svc2-test
| |
svc1-bench svc2-bench
\ /
\ /
\ /
\ /
notify
The build would pass only if the all branches have succeeded. Furthermore, we could fail a branch early and not execute the benchmarking if the tests fail for any given branch.
From reading the documentation I see how I can run parallel stages using group, but not how to put many stages in a single branch.
I guess my fallback solution would be to put combine test+benchmark in a single stage, but I think it would be nice to isolate them, especially since the dependencies may vary for each.
I was looking for something similar and found it answered here by the user cdieck.
This is how it looks in Blue Ocean.
Copying the same for quick reference:
pipeline {
agent none
stages {
stage("Example") {
failFast true
parallel {
stage("win7-vs2012") {
agent {
label "win7-vs2012"
}
stages {
stage("checkout (win7-vs2012)") {
steps {
echo "win7-vs2012 checkout"
}
}
stage("build (win7-vs2012)") {
steps {
echo "win7-vs2012 build"
}
}
stage("test (win7-vs2012)") {
steps {
build 'test-win7-vs2012'
}
}
}
}
stage("win10-vs2015") {
agent {
label "win10-vs2015"
}
stages {
stage("checkout (win10-vs2015)") {
steps {
echo "win10-vs2015 checkout"
}
}
stage("build (win10-vs2015)") {
steps {
echo "win10-vs2015 build"
}
}
stage("test (win10-vs2015)") {
steps {
build 'test-win10-vs2015'
}
}
}
}
stage("linux-gcc5") {
agent {
label "linux-gcc5"
}
stages {
stage("checkout (linux-gcc5)") {
steps {
echo "linux-gcc5 checkout"
}
}
stage("build (linux-gcc5)") {
steps {
echo "linux-gcc5 build"
}
}
stage("test (linux-gcc5)") {
steps {
build 'test-linux-gcc5'
}
}
}
}
}
}
}
}

how to pass 'eventBusIndex' parameter to EventBus annotation processor

I am just getting started to use the new Android Jack compiler and use the Greenrobot Eventbus.
I got it working after some trial-and-error but it only seems to work, when I specify the eventBusIndex parameter in 2 places - see code below:
android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
// TODO: why must I specify eventBusIndex twice? --> also for each buildVariant
arguments = [
'eventBusIndex': "com.tmtron.dscontrol.EventBusIndex"
]
}
}
}
// this is a workaround to specify the Manifest for AndroidAnnotations
// see: https://code.google.com/p/android/issues/detail?id=210753
applicationVariants.all { variant ->
variant.variantData.variantConfiguration.javaCompileOptions.annotationProcessorOptions
.arguments = [
'eventBusIndex': "com.tmtron.dscontrol.EventBusIndex"
, 'androidManifestFile': variant.outputs[0]?.processResources?.manifestFile?.absolutePath
]
}
}

Get GraphQL whole schema query

I want to get the schema from the server.
I can get all entities with the types but I'm unable to get the properties.
Getting all types:
query {
__schema {
queryType {
fields {
name
type {
kind
ofType {
kind
name
}
}
}
}
}
}
How to get the properties for type:
__type(name: "Person") {
kind
name
fields {
name
type {
kind
name
description
}
}
}
How can I get all types with the properties in only 1 request? Or ever better: How can I get the whole schema with the mutators, enums, types ...
Update
Using graphql-cli is now the recommended workflow to get and update your schema.
The following commands will get you started:
# install via NPM
npm install -g graphql-cli
# Setup your .graphqlconfig file (configure endpoints + schema path)
graphql init
# Download the schema from the server
graphql get-schema
You can even listen for schema changes and continuously update your schema by running:
graphql get-schema --watch
In case you just want to download the GraphQL schema, use the following approach:
The easiest way to get a GraphQL schema is using the CLI tool get-graphql-schema.
You can install it via NPM:
npm install -g get-graphql-schema
There are two ways to get your schema. 1) GraphQL IDL format or 2) JSON introspection query format.
GraphQL IDL format
get-graphql-schema ENDPOINT_URL > schema.graphql
JSON introspection format
get-graphql-schema ENDPOINT_URL --json > schema.json
or
get-graphql-schema ENDPOINT_URL -j > schema.json
For more information you can refer to the following tutorial: How to download the GraphQL IDL Schema
This is the query that GraphiQL uses (network capture):
query IntrospectionQuery {
__schema {
queryType {
name
}
mutationType {
name
}
subscriptionType {
name
}
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type {
...TypeRef
}
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
You can use GraphQL-JS's introspection query to get everything you'd like to know about the schema:
import { introspectionQuery } from 'graphql';
If you want just the information for types, you can use this:
{
__schema: {
types: {
...fullType
}
}
}
Which uses the following fragment from the introspection query:
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type { ...TypeRef }
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
`;
If that seems complicated, it's because fields can be arbitrarility deeply wrapped in nonNulls and Lists, which means that technically even the query above does not reflect the full schema if your fields are wrapped in more than 7 layers (which probably isn't the case).
You can see the source code for introspectionQuery here.
Using apollo cli:
npx apollo schema:download --endpoint=http://localhost:4000/graphql schema.json
Update
After getting sick of modifying my previous script all the time, I caved and made my own CLI tool gql-sdl. I still can't find a different tool that can download GraphQL SDL with zero config but would love for one to exist.
Basic usage:
$ gql-sdl https://api.github.com/graphql -H "Authorization: Bearer ghp_[redacted]"
directive #requiredCapabilities(requiredCapabilities: [String!]) on OBJECT | SCALAR | ARGUMENT_DEFINITION | INTERFACE | INPUT_OBJECT | FIELD_DEFINITION | ENUM | ENUM_VALUE | UNION | INPUT_FIELD_DEFINITION
"""Autogenerated input type of AbortQueuedMigrations"""
input AbortQueuedMigrationsInput {
"""The ID of the organization that is running the migrations."""
ownerId: ID!
"""A unique identifier for the client performing the mutation."""
clientMutationId: String
}
...
The header argument -H is technically optional but most GraphQL APIs require authentication via headers. You can also download the JSON response instead (--json) but that's a use case already well served by other tools.
Under the hood this still uses the introspection query provided by GraphQL.js, so if you're looking to incorporate this functionality into your own code see the example below.
Previous answer
Somehow I wasn't able to get any of the suggested CLI tools to output the schema in GraphQL's Schema Definition Language (SDL) instead of the introspection result JSON. I ended up throwing together a really quick Node script to make the GraphQL library do it for me:
const fs = require("fs");
const { buildClientSchema, getIntrospectionQuery, printSchema } = require("graphql");
const fetch = require("node-fetch");
async function saveSchema(endpoint, filename) {
const response = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query: getIntrospectionQuery() })
});
const graphqlSchemaObj = buildClientSchema((await response.json()).data);
const sdlString = printSchema(graphqlSchemaObj);
fs.writeFileSync(filename, sdlString);
}
saveSchema("https://example.com/graphql", "schema.graphql");
getIntrospectionQuery() has the complete introspection query you need to get everything, and then buildClientSchema() and printSchema() turns the JSON mess into GraphQL SDL.
Wouldn't be too difficult to make this into a CLI tool itself but that feels like overkill.
You can use the Hasura's graphqurl utility
npm install -g graphqurl
gq <endpoint> --introspect > schema.graphql
# or if you want it in json
gq <endpoint> --introspect --format json > schema.json
Full documentation: https://github.com/hasura/graphqurl
You can download a remote GraphQL server's schema with the following command. When the command succeeds, you should see a new file named schema.json in the current working directory.
~$ npx apollo-cli download-schema $GRAPHQL_URL --output schema.json
You can use GraphQL-Codegen with the ast-plugin
npm install --save graphql
npm install --save-dev #graphql-codegen/cli
npx graphql-codegen init
Follow the steps to generate the codegen.yml file
Once the tool is installed, you can use the plugin to download the schema which is schema-ast
The best is to follow the instruction on the page to install it… but basically:
npm install --save-dev #graphql-codegen/schema-ast
Then configure the codegen.yml file to set which schema(s) is/are the source of truth and where to put the downloaded schema(s) file:
schema:
- 'http://localhost:3000/graphql'
generates:
path/to/file.graphql:
plugins:
- schema-ast
config:
includeDirectives: true
I was also looking and came across this Medium article on GraphQL
The below query returned many details regarding schema, queries and their input & output params type.
fragment FullType on __Type {
kind
name
fields(includeDeprecated: true) {
name
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
type {
...TypeRef
}
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
query IntrospectionQuery {
__schema {
queryType {
name
}
mutationType {
name
}
types {
...FullType
}
directives {
name
locations
args {
...InputValue
}
}
}
}
You can use IntelliJ plugin JS GraphQL then IDEA will ask you create two files "graphql.config.json" and "graphql.schema.json"
Then you can edit "graphql.config.json" to point to your local or remote GraphQL server:
"schema": {
"README_request" : "To request the schema from a url instead, remove the 'file' JSON property above (and optionally delete the default graphql.schema.json file).",
"request": {
"url" : "http://localhost:4000",
"method" : "POST",
"README_postIntrospectionQuery" : "Whether to POST an introspectionQuery to the url. If the url always returns the schema JSON, set to false and consider using GET",
"postIntrospectionQuery" : true,
"README_options" : "See the 'Options' section at https://github.com/then/then-request",
"options" : {
"headers": {
"user-agent" : "JS GraphQL"
}
}
}
After that IDEA plugin will auto load schema from GraphQL server and show the schema json in the console like this:
Loaded schema from 'http://localhost:4000': {"data":{"__schema":{"queryType":{"name":"Query"},"mutationType":{"name":"Mutation"},"subscriptionType":null,"types":[{"kind":"OBJECT","name":"Query","description":"","fields":[{"name":"launche
Refer to https://stackoverflow.com/a/42010467/10189759
Would like to point out that if authentications are needed, that you probably cannot just use the config file generated from graphql init
You might have to do something like this, for example, using the github graphql API
{
"projects": {
"graphqlProjectTestingGraphql": {
"schemaPath": "schema.graphql",
"extensions": {
"endpoints": {
"dev": {
"url": "https://api.github.com/graphql",
"headers": {
"Authorization": "Bearer <Your token here>"
}
}
}
}
}
}
}
If you want to do it by your self, read these code:
There is a modular state-of-art tool 「graphql-cli」, consider looking at it. It uses package 「graphql」's buildClientSchema to build IDL .graphql file from introspection data.
graphql-cli get-schema :integrated into graphql-cli part 1
graphql-config EndpointsExtension :integrated into graphql-cli part 2
The graphql npm package's IntrospectionQuery does
query IntrospectionQuery {
__schema {
queryType {
name
}
mutationType {
name
}
subscriptionType {
name
}
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type {
...TypeRef
}
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
source
You could use apollo codegen:client. See https://github.com/apollographql/apollo-tooling#apollo-clientcodegen-output

Opening chrome should cause the extension to check the output of an API.How can this be possible?

Hi I am developing a website as my chrome extension.the extension periodically checks the output of a server file and then works according to the output of the server file.Now what I need is that presently it checks the output of the server file every 5 min.So what I need is that when the output of the server file changes at any time,at that moment I have to do some operations.How can I do this?
Here is my background.js
var myNotificationID = null;
var oldChromeVersion = !chrome.runtime;
chrome.windows.onCreated.addListener(function (){
updateIcon();
});
chrome.tabs.onCreated.addListener(function (){
updateIcon();
});
chrome.tabs.onUpdated.addListener(function (){
updateIcon();
});
function getGmailUrl() {
return "http://calpinemate.com/";
}
function isGmailUrl(url) {
return url.indexOf(getGmailUrl()) == 0;
}
chrome.windows.onCreated.addListener(function (){
updateIcon();
});
function onInit() {
updateIcon();
if (!oldChromeVersion) {
chrome.alarms.create('watchdog',{periodInMinutes:5,delayInMinutes: 0});
}
}
function onAlarm(alarm) {
if (alarm && alarm.name == 'watchdog') {
onWatchdog();
}
else {
updateIcon();
}
}
function onWatchdog() {
chrome.alarms.get('refresh', function(alarm) {
if (alarm) {
console.log('Refresh alarm exists. Yay.');
}
else {
updateIcon();
}
});
}
if (oldChromeVersion) {
updateIcon();
onInit();
}
else {
chrome.runtime.onInstalled.addListener(onInit);
chrome.alarms.onAlarm.addListener(onAlarm);
}
It is the updateIcon() which reads the server file.And when there is change in the output of server file,I have to call the updateIcon() itself.Presently only in every 5 min,the output is checked and updated in extension.But I need it to happen at the moment the status of server file changes.Anyone please help me.
In short,what I need is that when the output of API changes at any time at that time I have to call updateIcon().
Here is my updateIcon()
function updateIcon(){
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/2';
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
.....//something
}
else{
// do something
}
else {
alert("ERROR: status code " + req.status);
}
}
});
var url = urlPrefix + encodeURIComponent(localStorage.username) + urlSuffix;
req.open("GET", url);
req.send(null);
}
I need to periodically monitor the API for output.
You could use a WebSocket to maintain a persistent, two-way channel between the server and your extension.
But, considering that PHP does not have native support for WebSockets (i.e. you would need to use an external library) and the fact that the interaction will be infrequent (only at log-in/-out), it might be unnecessary overhead.
I suggest you communicate the login-status directly from your web-page to your extension. For a more detailed description of the process, see my answer to one similar question of yours.
UPDATE:
Since it turned out you don't have control of the domain you need to "monitor", there is unfortunately no other option (that I know of) than polling at frequent intervals on that server-resource.
If you are using a non-persistent background-page (which is advisable due to its resource-friendliness) you must use the chrome.alarms API, which allows at most 1 triggering per minute: (in order to reduce the load on the user's machine - note: to help debug your extension, this limit is no imposed on unpacked extensions).
If you decide to use a persistent background-page, you can use setInterval() with an arbitrarily smal period (in milliseconds):
setInterval(function() {
/* Check up on the server */
...
}, 30000); // <-- trigger every 30.000 milliseconds (== 30 seconds)