Migrating from WAF to GYP - trouble including library - node.js

I'm migrating an out of date npm package from WAF to GYP, but having a few problems getting everything working. It runs a WSCRIPT which seems to include a 3rd party library:
import Options
from os import unlink, symlink, popen, sys
from os.path import exists
srcdir = '.'
blddir = 'build'
VERSION = '0.0.2'
def set_options(opt):
opt.tool_options('compiler_cxx')
def configure(conf):
conf.check_tool('compiler_cxx')
conf.check_tool('node_addon')
print(sys.platform)
if sys.platform == 'darwin':
conf.check_tool('osx')
tc_framework = 'TelldusCore'
conf.env.append_value("FRAMEWORK_TC", tc_framework)
tc_frameworkpath = '/Library/Frameworks/TelldusCore.framework/'
conf.env.append_value("FRAMEWORKPATH_TC", tc_frameworkpath)
tc_lib = tc_frameworkpath + 'Headers/'
conf.env.append_value("CPPPATH_TC", tc_lib)
elif sys.platform == 'linux2':
conf.env.LIB_TC = 'telldus-core'
#conf.env.LIBPATH_TC = ['/usr/lib']
#conf.env.CCFLAGS_TC = ['-O0']
conf.env.CCDEFINES_TC = ['TC']
#conf.env.LINKFLAGS_TC = ['-g']
else:
raise ValueError("Dose not support: %r" % sys.platform)
def build(bld):
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
obj.target = 'telldus'
obj.source = 'telldus.cc'
obj.uselib = "TC"
Now I've tried to convert it to a binding.gyp script, but not sure how to include the library:
{
"targets": [
{
"target_name": "tellduscorejs2",
"sources": [ "tellduscorejs2.cpp" ],
"conditions": [
['OS=="mac"', {
'defines': [
'FRAMEWORK_TC=TelldusCore',
'FRAMEWORKPATH_TC="/Library/Frameworks/TelldusCore.framework/"',
'CPPPATH_TC="/Library/Frameworks/TelldusCore.framework/Headers/"'
]
}],
['OS=="linux"', {
'defines': [
'LIB_TC=telldus-core',
'CCDEFINES_TC=TC'
]
}]
],
'link_settings': {
'libraries': [
???
],
},
}
]
}
If anyone could point out if I'm on the right lines or what I need to change to include the library it'd be appreciated!

I've actually done this for the telldus-core project. See https://github.com/marchaos/telldus-core-js/
i've also added events for devices and sensors.

Related

How to get signals.py executed in django?

I run the following signals.py on (Ubuntu2204/WSL2 Windows 11) using Django 4.1.1 / Python 3.10
from .models import Sale
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
#receiver(m2m_changed, sender=Sale.positions.through)
def calculate_total_price(sender, instance, action, **kwargs):
print('action', action)
total_price = 0
if action == 'post_add' or action == 'post_remove':
for item in instance.get_positions():
total_price += item.price
instance.total_price = total_price
instance.save()
apps.py already signals in VSCode that signals is not used, this is also confirmed in the Django Debug Toolbar
from django.apps import AppConfig
class SalesConfig(AppConfig):
#default_auto_field = 'django.db.models.BigAutoField'
name = 'sales'
def ready(self):
import sales.signals
and then the __init__.py file
default_app_config = 'sales.apps.SalesConfig'
settings.py looks like this:
"""
Django settings for reports_proj project.
Generated by 'django-admin startproject' using Django 4.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-dbl^hk-m6-dz01+1i*hi5#rz4t90(y5s-cls1&0js5hj^ojo70"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"debug_toolbar",
# my apps
"customers",
"products",
"profiles",
"reports",
"sales.apps.SalesConfig",
# 3rd party
"crispy_forms",
]
CRISPY_TEMPLATE_PACK = "bootstrap4"
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"debug_toolbar.middleware.DebugToolbarMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "reports_proj.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / 'templates'],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "reports_proj.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / 'static',
BASE_DIR / 'sales' / 'static',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
INTERNAL_IPS = [
"127.0.0.1",
]
Any hint would be highly appreciated, the code looks ok to me it must be some dependency issue but I have no idea where to start looking really
I just noticed that your ready identation is not correct, causing the problem...
You should change this:
from django.apps import AppConfig
class SalesConfig(AppConfig):
#default_auto_field = 'django.db.models.BigAutoField'
name = 'sales'
def ready(self):
import sales.signals
To this:
from django.apps import AppConfig
class SalesConfig(AppConfig):
#default_auto_field = 'django.db.models.BigAutoField'
name = 'sales'
def ready(self):
from . import signals
Generally because no indentation the method became global function and it was not called as it should.

Groovy Mapping : Get all the values of a column

I have a json as below and I am trying to get the list of all the "dev" hosts using Groovy.
How can I do that ? I have attached a sample code that I am using currently, but that does not work for obvious reasons. I am new to Groovy.
{
"app1": {
"dev": [
"host1",
"host2"
],
"qa": null,
"uat": [
"host11"
]
},
"app2": {
"qa": null,
"stable": null,
"dev": [
"host3",
"host4"
]
}
CODE:
apiResponse = <Code which returns the json as mentioned above>
def parser = new JsonSlurper()
def host_list = parser.parseText(apiResponse)
dev_hosts = host_list[]['dev']
print dev_hosts
Expected Result:
['host1','host2','host3','host4']
There are any number of ways to do it and the best way may depend on knowing some more about the common usage patterns with respect to how many objects are in the top level JSON document etc, but the following does function:
String jsonInput = """
{
"app1": {
"dev": [
"host1",
"host2"
],
"qa": null,
"uat": [
"host11"
]
},
"app2": {
"qa": null,
"stable": null,
"dev": [
"host3",
"host4"
]
}
}"""
def object = new JsonSlurper().parseText(jsonInput)
def results = object.collect { it.value.dev }.flatten()
assert results == ['host1', 'host2', 'host3', 'host4']
def dev_hosts = host_list.values().collectMany{it['dev']}
edit: OP adjusted the specs: dev should be a variable and the lists
need to be flattened (at first level presumably).

How to find and get values from a json file which are in the same level?

I have a JSON file which looks like below. I am getting the parameters for name and product_version. Using both of them I need to get the relese_version and latest boolean value.
eg:- If var1 = section1 var2 = 2.6.0 then the release_version should be taken as 2.6.0.9 and latest as false in groovy.
file.json
{
"platforms": [
{
"name": "section1",
"versions": [
{
"product_version": "2.6.0",
"release_version": "2.6.0.9",
"latest": false
},
{
"product_version": "3.0.0",
"release_version": "3.0.0.3",
"latest": false
}
]
},
{
"name": "section2",
"versions": [
{
"product_version": "2.6.0",
"release_version": "2.6.0.9",
"latest": false
},
{
"product_version": "3.0.0",
"release_version": "3.0.0.3",
"latest": false
}
]
}
]
}
This is the code snippet I tried out.
filename = "file.json"
def jsonSlurper = new JsonSlurper()
parsed_json = jsonSlurper.parse(new File(filename))
release_tag = json.parsed_json.find {platforms.name == "section1".version[].product_version == "2.6.0".release_version}
println release_tag
But this didn't work. Please help me with this
You first have to find the platform by name (which could fail); next
find in the versions the product version. E.g.
def data = new groovy.json.JsonSlurper().parse("data.json" as File)
def name='section1'
def productVersion = '2.6.0'
// XXX
def result = data.platforms.find{ it.name == name }?.versions?.find{ it.product_version == productVersion }
assert result.release_version == '2.6.0.9'
assert result.latest == false
Note the use of the "elvis operator" after the first find to
short-circuit.
If you have to do many such lookups on the same data file, it might make
sense to shape the data into a better form for the lookup you are doing
(e.g. turn that into maps of maps for your two lookup keys)

How to translate groovy map to json

I have the below code in Jenkins pipeline:
stage ("distribution"){
steps{
script{
def rules = [
service_name: "core",
site_name: "*",
city_name: "*",
country_codes: ["*"]
]
amd_distribution_distribute_bundle distribution_rules: rules
}
}
}
As you can see, it's a map parameter. How can I convert it to the JSON file using Groovy code? At the end it should look like:
{
"distribution_rules": [
{
"service_name": "core*",
"site_name": "*",
"city_name": "*",
"country_codes": ["*"]
}
]
}
I tried the below command but it didn't help:
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
def call(Map parameters)
{
def DISTRIBUTION_RULES = parameters.distribution_rules
def json = new groovy.json.JsonBuilder()
json rootKey: "${DISTRIBUTION_RULES}"
writeFile file: 'rootKey', text: JsonOutput.toJson(json)
}
There is no need to mix JsonBuilder and JsonOutput in your amd_distribution_distribute_bundle.groovy file. The JsonOutput.toJson(map) method takes a regular Map and translates it to the JSON object equivalent. By default it creates a flat single line file. If you expect to get so-called pretty print, you need to use combination of JsonOutput.prettyPrint(JsonOutput.toJson(map)).
Flat print
import groovy.json.JsonOutput
def call(Map parameters) {
def DISTRIBUTION_RULES = parameters.distribution_rules
writeFile file: 'rootKey', text: JsonOutput.toJson([distribution_rules: [DISTRIBUTION_RULES]])
}
Output:
$ cat rootKey
{"distribution_rules":[{"service_name":"core","site_name":"*","city_name":"*","country_codes":["*"]}]}%
Pretty print
import groovy.json.JsonOutput
def call(Map parameters) {
def DISTRIBUTION_RULES = parameters.distribution_rules
writeFile file: 'rootKey', text: JsonOutput.prettyPrint(JsonOutput.toJson([distribution_rules: [DISTRIBUTION_RULES]]))
}
Output:
$ cat rootKey
{
"distribution_rules": [
{
"service_name": "core",
"site_name": "*",
"city_name": "*",
"country_codes": [
"*"
]
}
]
}%

Including runfiles in a filegroup

Im new to Bazel.
I thought id start by trying to build a simple nodejs project, it uses babel to do some transforming as part of the build process, the issue im having is I cant seem to find a way to get these transformed files into a filegroup.
Here's my BUILD file.
load("#build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary")
load("#bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar")
# Group all our initial code.
filegroup(
name = "src",
srcs = [
".babelrc",
"package.json",
"//config:src",
"//handlers:src",
"//migrations:src",
"//models:src",
"//services:src",
"//tasks:src",
"#dependencies//:node_modules",
],
)
# Group all our generated code.
filegroup(
name = "out",
srcs = [
"//:babel:runfiles" ### ???
],
)
nodejs_binary(
name = "babel",
entry_point = "babel-cli/bin/babel.js",
templated_args = [
".",
"--ignore node_modules,test/,migrations/,babel_bin_loader.js",
"-d out",
"--source-maps=both",
"--copy-files",
],
node_modules = "#nodejs_build_tools//:node_modules",
data = [
"//:src",
]
)
pkg_tar(
name = "build",
strip_prefix = "/",
package_dir = "/usr/src/app",
srcs = ["//:out"],
mode = "0755",
)
My issue is that im not sure how to reference the runfiles from my nodejs_binary rule.
https://github.com/bazelbuild/rules_nodejs/blob/master/internal/node/node.bzl#L130
Seems to indicate that there should be a :runfiles attribute or similar?
Thanks! :)
So turns out that the correct way to do this appears to be by using a genrule to actually call the configured nodejs binary. Eg.
## Artifact Construction ##
genrule(
name = "construct_artifact",
outs = ["artifact.tar"],
cmd = """./$(location babel) . --ignore bazel-
out,node_modules,text/,migrations/ -d out/ --source-maps=both --copy-files && tar cvf $# out/ """,
srcs = [
"//:src",
],
tools = [
"//:babel",
]
)

Resources