How do we refer to etc package from NixOS configuration? - nix

I want to get a path, which leads to nixos /etc location (any one of /run/current-system/etc or /nix/store/hashhere-etc-1.0). I use this path to configure pppd connect script, some kind of the following,
environment.etc."huawei" =
{ text = ''
/dev/ttyUSB0
38400
lock
crtscts
nodetach
noipdefault
# Below here what I've struggled
connect ${pkgs.etc}/${environment.etc."huawei-script".target}
'';
mode = "0777";
target = "ppp/peers/huawei"; };
I have tried to write ${pkgs.etc} or ${system.build.etc} or even ${environment.etc} resulting errors.
The directory structure is actually relative, but I think it's safer to use absolute path.
/nix/store/...etc.../ppp/peers
|- huawei
|- huawei.d
|- huawei.sh
|- huawei.chat

You can refer to path to file in /nix/store/...etc... like this:
{ config, pkgs, lib, ... }:
{
environment.etc."test".text = "helo";
environment.etc."test2".text = "${config.environment.etc."test".source.outPath}";
}
Now I have in /etc/test2:
$ cat /etc/test2
/nix/store/1igc2rf011jmrr3cprsgbdp3hhm5d4l0-etc-test

If I understand correctly your problem is you simply need to pass the string value of the target attribute to the huawei.text connect directive. As per the description for the target attribute the value is a path relative to /etc so you should be able to either:
Make the value of the connect directive the string literal connect /etc/ppp/peers/huawei or
make the etc.huaweiattribute set a recursive one so that the attributes can refer to each other then do
environment.etc.huawei = rec {
target = "ppp/peers/huawei";
text = ''...
# Below here what I've struggled
connect ${target}
'';
};

Sorry, I was overlook a fact where NixOS actually map any files in /nix/store/...etc../ into the /etc itself.
So, to refer to a file, it is better to use /etc directly.
connect /etc/${environment.etc."huawei-script".target}

Related

Using label path to check if file location exists

Is there an easy way to get hold of a path object so I can check if a given label path exists. Say for example if path.exists("#external_project_name//:filethatmightexist.txt"):. I can see that the repository context has this. But I need to have a wrapping repository rule. Is it possible to do this in a macro or Skylark native call instead?
Even with a repository_rule, I had a lot of trouble with this due to what you already pointed out:
if you create a Label with a path that doesn't exist, it will cause the build to fail
But if you're willing to do a repository rule, here's a possible solution...
In this example, my rule allows specification of a default configuration if a config file is not present. The configuration can be checked into .gitignore and overridden for individual developers, but work out of the box for most cases.
I think I understand why the ctx.actions have sibling arguments now, same idea here. The trick is config_file_location is a true label, and then config_file is a string attribute. I chose BUILD arbitrarily, but since all workspaces have a top level BUILD that's public seemed legit-ish.
WORKSPACE Definition
...
workspace(name="E02_mysql_database")
json_datasource_configuration(name="E02_datasources",
config_file_location="#E02_mysql_database//:BUILD",
config_file="database.json")
The definition for json_datasource_configuration looks like this:
json_datasource_configuration = repository_rule(
attrs = {
"config_file_location": attr.label(
doc="""
Path relative to the repository root for a datasource config file.
"""),
"config_file": attr.string(
doc="""
Config file, maybe absent
"""),
"default_config": attr.string(
# better way to do this?
default="None",
doc = """
If no config is at the path, then this will be the default config.
Should look something like:
{
"datasource_name": {
"host": "<host>"
"port": <port>
"password": "<password>"
"username": "<username>"
"jdbc_connection_string": "<optional>"
}
}
There can be more than datasource configured... maybe, eventually.
""",
),
},
local = True,
implementation = _json_config_impl,
)
Then in the rule I can test for the file existence, and if not present, do other logic.
def _json_config_impl(ctx):
"""
Allows you to specify a file on disk to use for data connection.
If you pass a default
"""
config_path = ctx.path(ctx.attr.config_file_location).dirname.get_child(ctx.attr.config_file)
config = ""
if config_path.exists:
config = ctx.read(config_path)
elif ctx.attr.default_config == "None":
fail("Could not find config at %s, you must supply a default_config if this is intentional" % ctx.attr.config_file)
else:
config = ctx.attr.default_config
...
probably too late to help, but your question is the only thing I found referencing this goal. If someone knows a better way I am looking for other options. It's complicated to explain to other developers why the rule has to work the way it does.
Also note, if you change the config file, you have to clean to get the workspace to re-read the config. I haven't been able to figure out any way to fix that. glob() does not work in the workspace.

Why can't waf find a path that exists?

Let's say I have x.y file in /mydir/a/b (on Linux)
When I run waf, it does not find the file.
def configure(context):
pass
def build(build_context):
build_context(source='/mydir/a/b/x.y',
rule='echo ${SRC} > ${TGT}',
target='test.out')
Result: source not found: '/mydir/a/b/x.y' in bld(features=[], idx=1, meths=['process_rule', 'process_source'] ...
Ok, maybe you want a relative path, Waf? And you are not telling me?
def build(context):
path_str = '/mydir/a/b'
xy_node = context.path.find_dir(path_str)
if xy_node is None:
exit ("Error: Failed to find path {}".format(path_str))
# just refer to the current script
orig_path = context.path.find_resource('wscript')
rel_path = xy_node.path_from(orig_path)
print "Relative path: ", rel_path
Result: Error: Failed to find path /mydir/a/b
But that directory exists! What's up with that?
And, by the way, the relative path for some subdirectory (which it can find) is one off. e.g. a/b under current directory results in relative path "../a/b". I'd expect "a/b"
In general there are (at least) two node objects in each context:
- path: is pointing to the location of the wscript
- root: is pointing to the filesystem root
So in you case the solution is to use context.root:
def build(context):
print context.path.abspath()
print context.root.abspath()
print context.root.find_dir('/mydir/a/b')
Hmm, looks like I found an answer on the waf-users group forum, answered by Mr. Nagy himself:
The source files must be present under the top-level directory. You
may either:
create a symlink to the source directory
copy the external source files into the build directory (which may cause problem if there is a structure of folders to copy)
set top to a common folder such as '/' (may require superuse permissions, so it is a bad idea in general)
The recommendation in conclusion is to add a symlink to the outside directory during the configuration step. I wonder how that would work, if I need this on both, Linux and Windows...
Just pass the Node to the copy rule instead of passing the string representing the path:
def build(build_context):
source_node = build_context.root.find_node('/mydir/a/b/x.y')
build_context(source=source_node,
rule='echo ${SRC} > ${TGT}',
target='test.out')
Waf will be able to find the file even if outside of the top level directory.

Iexpress - extraction path

I am going to create a self extracting archive but I have got a problem connecting with the default path of the extraction. I would like to extract my files in the same path as the self-extraction archive program. Unfortunately, the files are extracting in another path (C:\Users\computer\AppData\Temp\IXP000.TMP). Is it possible to set the path?
I can't find any direct way to do this with IExpress, but there is a trick we can apply.
But first I'll point out that this is really easy with something like 7-Zip's 7zCon.sfx module (if all you need to do is have the archive extract to the current directory, no questions asked). So you might just want to try something other than IExpress.
Anyhow, the problem with IExpress is that, at the time our install program runs, we're no longer in the directory of the original archive; the current directory is now something like %temp%\IXP000.TMP. So we need to find the directory of our parent process – kind of a pain. Once that's known, we can just xcopy the contents of the archive over to the destination folder.
In VBScript, it would look something like this:
Option Explicit
Dim objShell, objWMI
Dim objCmd, intMyPid, intMyParentPid, objMyParent
Set objShell = CreateObject("WScript.Shell")
Set objWMI = GetObject("winmgmts:root\cimv2")
Set objCmd = objShell.Exec("cmd.exe")
intMyPid = objWMI.Get("Win32_Process.Handle='" & objCmd.ProcessID & "'").ParentProcessId
objCmd.Terminate
intMyParentPid = objWMI.Get("Win32_Process.Handle='" & intMyPid & "'").ParentProcessId
Set objMyParent = objWMI.Get("Win32_Process.Handle='" & intMyParentPid & "'")
objShell.Run "xcopy /y * " & """" & Left(objMyParent.ExecutablePath, _
InStrRev(objMyParent.ExecutablePath, ".exe", -1, vbTextCompare) -1) &_
"\""", 0, True
Your install program would then be, eg: wscript extractToOriginalLocation.vbs //B.
(Inspired somewhat by the answer to this question.)
You could always use a cmd script and echo lines of code into files in specific directories

How do I derive physical path of a relative directory inside Config.groovy?

I am trying to set up Weceem using the source from GitHub. It requires a physical path definition for the uploads directory, and for a directory for appears to be used for writing searchable indexes. The default setting for uploads is:
weceem.upload.dir = 'file:/var/www/weceem.org/uploads/'
I would like to define those using relative paths like WEB-INF/resources/uploads. I tried a methodology I have used previously for accessing directories with relative path like this:
File uploadDirectory = ApplicationHolder.application.parentContext.getResource("WEB-INF/resources/uploads").file
def absoluteUploadDirectory = uploadDirectory.absolutePath
weceem.upload.dir = 'file:'+absoluteUploadDirectory
However, 'parentContext' under ApplicationHolder.application is NULL. Can anyone offer a solution to this that would allow me to use relative paths?
look at your Config.groovy you should have (maybe it is commented)
// locations to search for config files that get merged into the main config
// config files can either be Java properties files or ConfigSlurper scripts
// "classpath:${appName}-config.properties", "classpath:${appName}-config.groovy",
grails.config.locations = [
"file:${userHome}/.grails/${appName}-config.properties",
"file:${userHome}/.grails/${appName}-config.groovy"
]
Create Conig file in deployment server
"${userHome}/.grails/${appName}-config.properties"
And define your prop (even not relative path) in that config file.
To add to Aram Arabyan's response, which is correct, but lacks an explanation:
Grails apps don't have a "local" directory, like a PHP app would have. They should be (for production) deployed in a servlet container. The location of that content is should not be considered writable, as it can get wiped out on the next deployment.
In short: think of your deployed application as a compiled binary.
Instead, choose a specific location somewhere on your server for the uploads to live, preferably outside the web server's path, so they can't be accessed directly. That's why Weceem defaults to a custom folder under /var/www/weceem.org/.
If you configure a path using the externalized configuration technique, you can then have a path specific to the server, and include a different path on your development machine.
In both cases, however, you should use absolute paths, or at least paths relative to known directories.
i.e.
String base = System.properties['base.dir']
println "config: ${base}/web-app/config/HookConfig.grooy"
String str = new File("${base}/web-app/config/HookConfig.groovy").text
return new ConfigSlurper().parse(str)
or
def grailsApplication
private getConfig() {
String str = grailsApplication.parentContext.getResource("config/HookConfig.groovy").file.text
return new ConfigSlurper().parse(str)
}

how to set the path to where aapt add command adds the file

I'm using aapt tool to remove some files from different folders of my apk. This works fine.
But when I want to add files to the apk, the aapt tool add command doesn't let me specify the path to where I want the file to be added, therefore I can add files only to the root folder of the apk.
This is strange because I don't think that developers would never want to add files to a subfolder of the apk (res folder for example). Is this possible with aapt or any other method? Cause removing files from any folder works fine, and adding file works only for the root folder of the apk. Can't use it for any other folder.
Thanks
The aapt tool retains the directory structure specified in the add command, if you want to add something to an existing folder in an apk you simply must have a similar folder on your system and must specify each file to add fully listing the directory. Example
$ aapt list test.apk
res/drawable-hdpi/pic1.png
res/drawable-hdpi/pic2.png
AndroidManifest.xml
$ aapt remove test.apk res/drawable-hdpi/pic1.png
$ aapt add test.apk res/drawable-hdpi/pic1.png
The pic1.png that will is added resides in a folder in the current working directory of the terminal res/drawable-hdpi/ , hope this answered your question
There is actually a bug in aapt that will make this randomly impossible. The way it is supposed to work is as the other answer claims: paths are kept, unless you pass -k. Let's see how this is implemented:
The flag that controls whether the path is ignored is mJunkPath:
bool mJunkPath;
This variable is in a class called Bundle, and is controlled by two accessors:
bool getJunkPath(void) const { return mJunkPath; }
void setJunkPath(bool val) { mJunkPath = val; }
If the user specified -k at the command line, it is set to true:
case 'k':
bundle.setJunkPath(true);
break;
And, when the data is being added to the file, it is checked:
if (bundle->getJunkPath()) {
String8 storageName = String8(fileName).getPathLeaf();
printf(" '%s' as '%s'...\n", fileName, storageName.string());
result = zip->add(fileName, storageName.string(),
bundle->getCompressionMethod(), NULL);
} else {
printf(" '%s'...\n", fileName);
result = zip->add(fileName, bundle->getCompressionMethod(), NULL);
}
Unfortunately, the one instance of Bundle used by the application is allocated in main on the stack, and there is no initialization of mJunkPath in the constructor, so the value of the variable is random; without a way to explicitly set it to false, on my system I (seemingly deterministically) am unable to add files at specified paths.
However, you can also just use zip, as an APK is simply a Zip file, and the zip tool works fine.
(For the record, I have not submitted the trivial fix for this as a patch to Android yet, if someone else wants to the world would likely be a better place. My experience with the Android code submission process was having to put up with an incredibly complex submission mechanism that in the end took six months for someone to get back to me, in some cases with minor modifications that could have just been made on their end were their submission process not so horribly complex. Given that there is a really easy workaround to this problem, I do not consider it important enough to bother with all of that again.)

Resources