I'm trying to add the gin package in the BUILD file. When I build the file I get the following error
no such package '#com_github_gin_gonic_gin//go_default_library': The repository '#com_github_gin_gonic_gin' could not be resolved: Repository '#com_github_gin_gonic_gin' is not defined and referenced by
load("#io_bazel_rules_go//go:def.bzl", "go_library")
load("#bazel_gazelle//:def.bzl", "gazelle")
package(default_visibility = ["//visibility:public"])
go_library(
name = "",
srcs = [""],
importpath = "",
visibility = ["//visibility:public"],
deps = [
"#com_github_gin_gonic_gin//go_default_library",
"#io_k8s_client_go//kubernetes",
"#io_k8s_client_go//tools/clientcmd",
"#io_k8s_client_go//util/homedir",
],
)
In your workspace file try calling go_rules_dependencies() first and then load other dependencies with respect to gin packages.
Is there a good solution on how to include third party pre compiled binaries like imagemagick into an electron app? there are node.js modules but they are all wrappers or native binding to the system wide installed libraries. I wonder if it's possible to bundle precompiled binaries within the distribution.
Here's another method, tested with Mac and Windows so far. Requires 'app-root-dir' package, doesn't require adding anything manually to node_modules dir.
Put your files under resources/$os/, where $os is either "mac", "linux", or "win". The build process will copy files from those directories as per build target OS.
Put extraFiles option in your build configs as follows:
package.json
"build": {
"extraFiles": [
{
"from": "resources/${os}",
"to": "Resources/bin",
"filter": ["**/*"]
}
],
Use something like this to determine the current platform.
get-platform.js
import { platform } from 'os';
export default () => {
switch (platform()) {
case 'aix':
case 'freebsd':
case 'linux':
case 'openbsd':
case 'android':
return 'linux';
case 'darwin':
case 'sunos':
return 'mac';
case 'win32':
return 'win';
}
};
Call the executable from your app depending on env and OS. Here I am assuming built versions are in production mode and source versions in other modes, but you can create your own calling logic.
import { join as joinPath, dirname } from 'path';
import { exec } from 'child_process';
import appRootDir from 'app-root-dir';
import env from './env';
import getPlatform from './get-platform';
const execPath = (env.name === 'production') ?
joinPath(dirname(appRootDir.get()), 'bin'):
joinPath(appRootDir.get(), 'resources', getPlatform());
const cmd = `${joinPath(execPath, 'my-executable')}`;
exec(cmd, (err, stdout, stderr) => {
// do things
});
I think I was using electron-builder as base, the env file generation comes with it. Basically it's just a JSON config file.
See UPDATE below (this method isn't ideal now).
I did find a solution to this, but I have no idea if this is considered best practice. I couldn't find any good documentation for including 3rd party precompiled binaries, so I just fiddled with it until it finally worked with my ffmpeg binary. Here's what I did (starting with the electron quick start, node.js v6):
Mac OS X method
From the app directory I ran the following commands in Terminal to include the ffmpeg binary as a module:
mkdir node_modules/ffmpeg
cp /usr/local/bin/ffmpeg node_modules/ffmpeg/
cd node_modules/.bin
ln -s ../ffmpeg/ffmpeg ffmpeg
(replace /usr/local/bin/ffmpeg with your current binary path, download it from here) Placing the link allowed electron-packager to include the binary I saved to node_modules/ffmpeg/.
Then to get the bundled app path (so that I could use an absolute path for my binary... relative paths didn't seem to work no matter what I did) I installed the npm package app-root-dir by running the following command:
npm i -S app-root-dir
Now that I had the root app directory, I just append the subfolder for my binary and spawned from there. This is the code that I placed in renderer.js:.
var appRootDir = require('app-root-dir').get();
var ffmpegpath=appRootDir+'/node_modules/ffmpeg/ffmpeg';
console.log(ffmpegpath);
const
spawn = require( 'child_process' ).spawn,
ffmpeg = spawn( ffmpegpath, ['-i',clips_input[0]]); //add whatever switches you need here
ffmpeg.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
});
ffmpeg.stderr.on( 'data', data => {
console.log( `stderr: ${data}` );
});
Windows Method
Open your electron base folder (electron-quick-start is the default name), then go into the node_modules folder. Create a folder there called ffmpeg, and copy your static binary into this directory. Note: it must be the static version of your binary, for ffmpeg I grabbed the latest Windows build here.
To get the bundled app path (so that I could use an absolute path for my binary... relative paths didn't seem to work no matter what I did) I installed the npm package app-root-dir by running the following command from a command prompt in my app directory:
npm i -S app-root-dir
Within your node_modules folder, navigate to the .bin subfolder. You need to create a couple of text files here to tell node to include the binary exe file you just copied. Use your favorite text editor and create two files, one named ffmpeg with the following contents:
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../ffmpeg/ffmpeg" "$#"
ret=$?
else
node "$basedir/../ffmpeg/ffmpeg" "$#"
ret=$?
fi
exit $ret
And the the second text file, named ffmpeg.cmd:
#IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\ffmpeg\ffmpeg" %*
) ELSE (
#SETLOCAL
#SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\ffmpeg\ffmpeg" %*
)
Next you can run ffmpeg in your Windows electron distribution (in renderer.js) as follows (I'm using the app-root-dir node module as well). Note the quotes added to the binary path, if your app is installed to a directory with spaces (eg C:\Program Files\YourApp) it won't work without these.
var appRootDir = require('app-root-dir').get();
var ffmpegpath = appRootDir + '\\node_modules\\ffmpeg\\ffmpeg';
const
spawn = require( 'child_process' ).spawn;
var ffmpeg = spawn( 'cmd.exe', ['/c', '"'+ffmpegpath+ '"', '-i', clips_input[0]]); //add whatever switches you need here, test on command line first
ffmpeg.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
});
ffmpeg.stderr.on( 'data', data => {
console.log( `stderr: ${data}` );
});
UPDATE: Unified Simple Method
Well, as time as rolled on and Node has updated, this method is no longer the easiest way to include precompiled binaries. It still works, but when npm install is run the binary folders under node_modules will be deleted and have to be replaced again. The below method works for Node v12.
This new method obviates the need to symlink, and works similarly for Mac and Windows. Relative paths seem to work now.
You will still need appRootDir: npm i -S app-root-dir
Create a folder under your app's root directory named bin and place your precompiled static binaries here, I'm using ffmpeg as an example.
Use the following code in your renderer script:
const appRootDir = require('app-root-dir').get();
const ffmpegpath = appRootDir + '/bin/ffmpeg';
const spawn = require( 'child_process' ).spawn;
const child = spawn( ffmpegpath, ['-i', inputfile, 'out.mp4']); //add whatever switches you need here, test on command line first
child.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
});
child.stderr.on( 'data', data => {
console.log( `stderr: ${data}` );
});
The above answers helped me figure out how it could done but there is a much efficient way to distribute binary files.
Taking cues from tsuriga's answer, here is my code:
Note: replace or add OS path as required.
Update - 4 Dec 2020
This answer has been updated. Find the previous code to the bottom of this answer.
Download the needed packages
yarn add electron-root-path electron-is-packaged
# or
npm i electron-root-path electron-is-packaged
Create a directory ./resources/mac/bin
Place you binaries inside this folder
Create a file ./app/binaries.js and paste the following code:
import path from 'path';
import { rootPath as root } from 'electron-root-path';
import { isPackaged } from 'electron-is-packaged';
import { getPlatform } from './getPlatform';
const IS_PROD = process.env.NODE_ENV === 'production';
const binariesPath =
IS_PROD && isPackaged // the path to a bundled electron app.
? path.join(root, './Contents', './Resources', './bin')
: path.join(root, './build', getPlatform(), './bin');
export const execPath = path.resolve(
path.join(binariesPath, './exec-file-name')
);
Create a file ./app/get-platform.js and paste the following code:
'use strict';
import { platform } from 'os';
export default () => {
switch (platform()) {
case 'aix':
case 'freebsd':
case 'linux':
case 'openbsd':
case 'android':
return 'linux';
case 'darwin':
case 'sunos':
return 'mac';
case 'win32':
return 'win';
}
};
Add these lines inside the ./package.json file:
"build": {
....
"extraFiles": [
{
"from": "resources/mac/bin",
"to": "Resources/bin",
"filter": [
"**/*"
]
}
],
....
},
import binary as:
import { execPath } from './binaries';
#your program code:
var command = spawn(execPath, arg, {});
Why this is better?
The above answers require an additional package called app-root-dir
tsuriga's answer doesn't handle the (env=production) build or the pre-packed versions properly. He/she has only taken care of development and post-packaged versions.
Previous answer
Avoid using electron.remote as it is getting depreciated
app.getAppPath might throw errors in the main process.
./app/binaries.js
'use strict';
import path from 'path';
import { remote } from 'electron';
import getPlatform from './get-platform';
const IS_PROD = process.env.NODE_ENV === 'production';
const root = process.cwd();
const { isPackaged, getAppPath } = remote.app;
const binariesPath =
IS_PROD && isPackaged
? path.join(path.dirname(getAppPath()), '..', './Resources', './bin')
: path.join(root, './resources', getPlatform(), './bin');
export const execPath = path.resolve(path.join(binariesPath, './exec-file-name'));
tl;dr:
yes you can! but it requires you to write your own self-contained addon which does not make any assumptions on system libraries. Moreover in some cases you have to make sure that your addon is compiled for the desired OS.
Lets break this question in several parts:
- Addons (Native modules):
Addons are dynamically linked shared objects.
In other words you can just write your own addon with no dependency on system wide libraries (e.g. by statically linking required modules) containing all the code you need.
You have to consider that such approach is OS-specific, meaning that you need to compile your addon for each OS that you want to support! (depending on what other libraries you may use)
- Native modules for electron:
The native Node modules are supported by Electron, but since Electron is using a different V8 version from official Node, you have to manually specify the location of Electron's headers when building native modules
This means that a native module which has been built against node headers must be rebuilt to be used inside electron. You can find how in electron docs.
- Bundle modules with electron app:
I suppose you want to have your app as a stand-alone executable without requiring users to install electron on their machines. If so, I can suggest using electron-packager.
following Ganesh answer's which was really a great help, in my case what was working in binaries.js (for a mac build - did not test for windows or linux) was:
"use strict";
import path from "path";
import { app } from "electron";
const IS_PROD = process.env.NODE_ENV === "production";
const root = process.cwd();
const { isPackaged } = app;
const binariesPath =
IS_PROD && isPackaged
? path.join(process.resourcesPath, "./bin")
: path.join(root, "./external");
export const execPath = path.join(binariesPath, "./my_exec_name");
Considering that my_exec_name was in the folder ./external/bin and copied in the app package in ./Resources/bin. I did not use the get_platforms.js script (not needed in my case). app.getAppPath() was generating a crash when the app was packaged.
Hope it can help.
Heavily based on Ganesh's answer, but simplified somewhat. Also I am using the Vue CLI Electron Builder Plugin so the config has to go in a slightly different place.
Create a resources directory. Place all your files in there.
Add this to vue.config.js:
module.exports = {
pluginOptions: {
electronBuilder: {
builderOptions: {
...
"extraResources": [
{
"from": "resources",
"to": ".",
"filter": "**/*"
}
],
...
}
}
}
}
Create a file called resources.ts in your src folder, with these contents:
import path from 'path';
import { remote } from 'electron';
// Get the path that `extraResources` are sent to. This is `<app>/Resources`
// on macOS. remote.app.getAppPath() returns `<app>/Resources/app.asar` so
// we just get the parent directory. If the app is not packaged we just use
// `<current working directory>/resources`.
export const resourcesPath = remote.app.isPackaged ?
path.dirname(remote.app.getAppPath()) :
path.resolve('resources');
Note I haven't tested this on Windows/Linux but it should work assuming app.asar is in the resources directory on those platforms (I assume so).
Use it like this:
import { resourcesPath } from '../resources'; // Path to resources.ts
...
loadFromFile(resourcesPath + '/your_file');
I have just upgraded an Android project's build.gradle to use build version 3.3.0
com.android.tools.build:gradle:3.3.0
Doing so has created this warning:
WARNING: API 'variant.getAssemble()' is obsolete and has been replaced with 'variant.getAssembleProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
To determine what is calling variant.getAssemble(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.
Affected Modules: app
It is caused by this code in the app build.gradle:
android.applicationVariants.all { variant ->
variant.assemble.doLast {
variant.outputs.each { output ->
def apk = variant.outputs[0].outputFile
File versionInfo = new File(apk.parent, "versionInfo.properties")
versionInfo.text = "versionCode=${android.defaultConfig.versionCode}\nversionName=${android.defaultConfig.versionName}"
copy {
from "${versionInfo}"
into "$project.projectDir/temp_archive"
}
}
}
}
I haven't been able to find where I can rewrite this to make the warning disappear. I tried to follow this Stack Overflow post, but didn't make any progress. Any suggestions would be greatly appreciated.
I found a potential solution that has resolved the warning. Below is the code I am using. Leaving the question for now in case there is a better solution.
android.applicationVariants.all { variant ->
variant.getAssembleProvider().get().doLast {
variant.outputs.each { output ->
def apk = variant.outputs[0].outputFile
File versionInfo = new File(apk.parent, "versionInfo.properties")
versionInfo.text = "versionCode=${android.defaultConfig.versionCode}\nversionName=${android.defaultConfig.versionName}"
copy {
from "${versionInfo}"
into "$project.projectDir/temp_archive"
}
}
}
}
I'm used to working with Makefiles but my current project uses .qbs files. How do I run a simple terminal command through qbs without creating or requiring files? Similar to a phony rule in make.
The following works and shows "awesome" in my terminal.
import qbs 1.0
Project {
name: "cli"
Product {
name: "helloworld"
type: "application"
files: "TEST.c"
Depends { name: "cpp" }
}
Product {
type: ["custom-image"]
Depends { name: "helloworld" }
Rule {
inputsFromDependencies: ["application"]
Artifact {
fileTags: ["custom-image"]
}
prepare: {
var cmd = new Command("echo", "awesome")
return cmd
}
}
}
}
However I have to touch my dummy TEST.c file before each run. Without the helloworld dependency the Rule does not run.
Any ideas? Thank you very much!
It's buried in the documentation in a very non obvious place and further obscured by Command (which is not the correct way, lol). I've had your problem too.
What you need is this:
http://doc.qt.io/qbs/jsextension-process.html
I'm not sure what your end goal is but you could use Transformer{} instead of a Rule{}. The biggest difference between a Rule{} and a Transformer{} is you don't need any inputs for the Transformer{} to run.
Also see Transformer.alwaysRun property.
https://doc.qt.io/qbs/transformer-item.html
I'm having a hell of a time with Karma/Jasmine. I'm just trying to run the example specs from Jasmine's site.
When I run jasmine on command line, the tests run fine. However, if I try to run them using Karma test runner, I have a multitude of problems.
Here's My File Structure
Here's my karma.conf.js file:
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'node_modules/requirejs/require.js',
'**/test-main.js', {
pattern: 'spec/jasmine_examples/*.js',
included: false
}
],
// list of files to exclude
exclude: ['**/*conf.js'],
...port,browser etc.
Here's my test.main.js file
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
When I run karma start, I get a 404 that PlayerTest.js and SongTest.js are not under base/. However they are loaded and located in base/spec/jasmine_examples. In addition, PlayerTest.js throws an error "module not defined".
Honestly, what am I doing wrong?
I think you need to refer to the karma-requirejs and the karma-jasmine plugins in the karma.conf.js file -
config.set({
plugins: [
'karma-jasmine',
'karma-requirejs'
],
From karma doc, it states:
Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM).
Additional information can be found in plugins.
You will not need to have require.js in the files section.