diff --git a/README.md b/README.md index cdb418f..8581f87 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # NetworkManager to Nix -This is a really dumb script that converts every .nmconnection file in the current directory to the nix code that is expected by `networking.networkmanager.ensure-profiles.profiles` which was introduced in [NixOS/nixpkgs/#254647](https://github.com/NixOS/nixpkgs/pull/254647) -You will have to do some manual escaping for connection names with special characters +This is a dumb script that converts every .nmconnection file in the current directory to the nix code that is expected by `networking.networkmanager.ensure-profiles.profiles` which was introduced in [NixOS/nixpkgs/#254647](https://github.com/NixOS/nixpkgs/pull/254647) +You want to pipe the output of this program through some formatter, for example `nixfmt` You probably want to run this script in `/etc/NetworkManager/system-connections/` (default profile storage) or `/run/NetworkManager/system-connections` (temporary profile storage) both of the folders are only readable by the root user so you need to execute the script with root permissions aka sudo. For more details about the locations feel free to read [redhat's docs](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/configuring_and_managing_networking/assembly_networkmanager-connection-profiles-in-keyfile-format_configuring-and-managing-networking) diff --git a/nm2nix.py b/nm2nix.py index c73bff1..f4f41b9 100644 --- a/nm2nix.py +++ b/nm2nix.py @@ -1,21 +1,30 @@ -from os import listdir +from os import listdir, getpid +from subprocess import check_output from os.path import isfile, join import configparser +import tempfile +import json + path = "./" files = [f for f in listdir(path) if isfile(join(path, f))] nmfiles = [f for f in files if f.endswith(".nmconnection")] -print("{") +jsonConfigs = {} + for i in nmfiles: config = configparser.ConfigParser(delimiters=('=', )) config.read(i) connection_name = i.removesuffix(".nmconnection") - print(f" {connection_name} = {{") + jsonConfigs[connection_name] = {} for section in config.sections(): - print(f" {section} = {{") + jsonConfigs[connection_name][section] = {} for key in config[section]: - print(f' {key} = "{config[section][key]}";') - print(" };") - print(" };") -print("};") + jsonConfigs[connection_name][section][key] = config[section][key] + +tf = tempfile.TemporaryFile("w+") +jsonConfigs = json.dump(jsonConfigs, tf) +tf.flush() + + +print(check_output(["nix-instantiate", "--expr", "--eval", f"builtins.fromJSON (builtins.readFile \"/proc/{getpid()}/fd/{tf.fileno()}\")"], text=True)) # noqa: E501