Skip to content

Commit

Permalink
cli
Browse files Browse the repository at this point in the history
  • Loading branch information
domenkozar committed Jul 27, 2023
1 parent 4d227ef commit edb1c7b
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 30 deletions.
2 changes: 1 addition & 1 deletion .envrc
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ set -euo pipefail
# External users should use `source_url` to load this file
source_env ./direnvrc

use devenv
use devenv
4 changes: 1 addition & 3 deletions devenv.nix
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
{ inputs, pkgs, lib, config, ... }:

{
env = {
DEVENV_NIX = inputs.nix.packages.${pkgs.stdenv.system}.nix;
};
env.DEVENV_NIX = inputs.nix.packages.${pkgs.stdenv.system}.nix;

packages = [
pkgs.cairo
Expand Down
27 changes: 15 additions & 12 deletions src/devenv/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import subprocess
import time
import re
import sys
from filelock import FileLock
from contextlib import suppress
from pathlib import Path
Expand Down Expand Up @@ -45,7 +46,7 @@ def run_nix(command: str) -> str:
command_flags = " ".join(ctx.obj['command_flags'])
return run_command(f"nix {flags} {command} {command_flags}")

def run_command(command: str) -> str:
def run_command(command: str, disable_stderr=False) -> str:
if command.startswith("nix"):
if os.environ.get("DEVENV_NIX"):
nix = os.path.join(os.environ["DEVENV_NIX"], "bin")
Expand All @@ -61,6 +62,8 @@ def run_command(command: str) -> str:
check=True,
env=os.environ.copy(),
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=None if not disable_stderr else subprocess.DEVNULL,
universal_newlines=True).stdout.strip()
except subprocess.CalledProcessError as e:
if e.returncode == 130:
Expand Down Expand Up @@ -214,8 +217,8 @@ def get_dev_environment(ctx, is_shell=False):
action = suppress()
with action:
gc_root = os.path.join(os.environ['DEVENV_GC'], 'shell')
env = run_nix(f"print-dev-env --impure --profile '{gc_root}'")
run_command(f"nix-env -p '{gc_root}' --delete-generations old")
env = run_nix(f"print-dev-env --profile '{gc_root}'")
run_command(f"nix-env -p '{gc_root}' --delete-generations old", disable_stderr=True)
symlink_force(Path(f'{ctx.obj["gc_project"]}-shell'), gc_root)
return env, gc_root

Expand Down Expand Up @@ -254,7 +257,7 @@ def symlink_force(src, dst):
def up(ctx, command):
with log_task('Building processes'):
ctx.invoke(assemble)
procfilescript = run_nix(f"build --no-link --print-out-paths --impure '.#procfileScript'")
procfilescript = run_nix(f"build --no-link --print-out-paths '.#procfileScript'")
with open(procfilescript, 'r') as file:
contents = file.read().strip()
if contents == '':
Expand All @@ -263,18 +266,16 @@ def up(ctx, command):
else:
log('Starting processes ...', level="info")
add_gc('procfilescript', procfilescript)
# TODO: print output to stdout
#run_command(procfilescript + ' ' + (command or ''))
args = [] if not command else [command]
subprocess.run([procfilescript] + args)
os.execv(procfilescript, args)

@cli.command()
@click.argument('name')
@click.pass_context
def search(ctx, name):
"""Search packages matching NAME in nixpkgs input."""
ctx.invoke(assemble)
options = run_nix(f"build --no-link --print-out-paths '.#optionsJSON' --impure")
options = run_nix(f"build --no-link --print-out-paths '.#optionsJSON' ")
search = run_nix(f"search --json nixpkgs {name}")

with open(Path(options) / 'share' / 'doc' / 'nixos' / 'options.json') as f:
Expand Down Expand Up @@ -339,6 +340,7 @@ def container(ctx, registry, copy, copy_args, docker_run, container_name):
# copy container
if copy or docker_run:
with log_task(f'Copying {container_name} container'):
# we need --impure here for DEVENV_CONTAINER
copy_script = run_nix(f"build --print-out-paths --no-link \
--impure .#devenv.containers.\"{container_name}\".copyScript")

Expand All @@ -351,8 +353,9 @@ def container(ctx, registry, copy, copy_args, docker_run, container_name):
check=True)

if docker_run:
with log_task(f'Starting {container_name} container'):
docker_script = run_nix(f"build --print-out-paths --no-link --impure \
log(f'Starting {container_name} container', level="info")
# we need --impure here for DEVENV_CONTAINER
docker_script = run_nix(f"build --print-out-paths --no-link --impure \
.#devenv.containers.\"{container_name}\".dockerRun")

subprocess.run(docker_script)
Expand All @@ -371,7 +374,7 @@ def info(ctx):
inputs = matches.group(1)
else:
inputs = ""
info_ = run_nix("eval --raw '.#info' --impure")
info_ = run_nix("eval --raw '.#info'")
click.echo(f"{inputs}\n{info_}")

@cli.command()
Expand Down Expand Up @@ -449,7 +452,7 @@ def ci(ctx):
output_path = run_nix(f"build --no-link --print-out-paths --impure .#ci")
add_gc('ci', output_path)

@cli.command()
@cli.command(hidden=True)
@click.pass_context
def print_dev_env(ctx):
env, _ = get_dev_environment(ctx)
Expand Down
2 changes: 1 addition & 1 deletion src/devenv/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def __init__(self, message,):

def __enter__(self):
prefix = click.style("•", fg="blue")
click.echo(f"{prefix} {self.message} ...", nl=False)
click.echo(f"{prefix} {self.message} ...")

def __exit__(self, exc, *args):
if exc:
Expand Down
5 changes: 4 additions & 1 deletion src/modules/flake.tmpl.nix
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@
specialArgs = inputs // { inherit inputs pkgs; };
modules = [
(inputs.devenv.modules + /top-level.nix)
{ devenv.cliVersion = "${version}"; }
{
devenv.cliVersion = "${version}";
devenv.root = devenv_root;
}
] ++ (map importModule (devenv.imports or [ ])) ++ [
./devenv.nix
(devenv.devenv or { })
Expand Down
21 changes: 9 additions & 12 deletions src/modules/top-level.nix
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ in
root = lib.mkOption {
type = types.str;
internal = true;
default = builtins.getEnv "PWD";
};

dotfile = lib.mkOption {
Expand Down Expand Up @@ -145,20 +146,16 @@ in
;

config = {
# TODO: figure out how to get relative path without impure mode
devenv.root = lib.mkDefault (
let
pwd = builtins.getEnv "PWD";
in
if pwd == "" then
throw ''
assertions = [
{
assertion = config.devenv.root != "";
message = ''
devenv was not able to determine the current directory.
Make sure Nix runs with the `--impure` flag.
See https://devenv.sh/guides/using-with-flakes/
''
else pwd
);
See https://devenv.sh/guides/using-with-flakes/ how to use it with flakes.
'';
}
];
devenv.dotfile = config.devenv.root + "/.devenv";
devenv.state = config.devenv.dotfile + "/state";
devenv.profile = profile;
Expand Down

0 comments on commit edb1c7b

Please sign in to comment.