nix

package
v0.0.0-...-3f9dac1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 7, 2025 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Overview

Package nix provides Go API for nix. Internally this is a wrapper around the nix command line utilities. I'd love to use a go SDK instead, and drop the dependency on the CLI. The dependency means that users need to install nix, before using devbox. Unfortunately, that go sdk does not exist. We would have to implement it.

Index

Constants

View Source
const (
	Version2_12 = nix.Version2_12
	Version2_13 = nix.Version2_13
	Version2_14 = nix.Version2_14
	Version2_15 = nix.Version2_15
	Version2_16 = nix.Version2_16
	Version2_17 = nix.Version2_17
	Version2_18 = nix.Version2_18
	Version2_19 = nix.Version2_19
	Version2_20 = nix.Version2_20
	Version2_21 = nix.Version2_21
	Version2_22 = nix.Version2_22
	Version2_23 = nix.Version2_23
	Version2_24 = nix.Version2_24
	Version2_25 = nix.Version2_25

	MinVersion = nix.Version2_12
)
View Source
const DefaultPriority = 5
View Source
const ProfilePath = ".devbox/nix/profile/default"

ProfilePath contains the contents of the profile generated via `nix-env --profile ProfilePath <command>` or `nix profile install --profile ProfilePath <package...>` Instead of using directory, prefer using the devbox.ProfileDir() function that ensures the directory exists.

Variables

View Source
var (
	ErrPackageNotFound     = errors.New("package not found")
	ErrPackageNotInstalled = errors.New("package not installed")
)
View Source
var Default = nix.Default
View Source
var ErrPriorityConflict = errors.New("priority conflict")
View Source
var ErrUnknownServiceManager = errors.New("unknown service manager")

Functions

func AtLeast

func AtLeast(version string) bool

func BinaryInstalled

func BinaryInstalled() bool

func Build

func Build(ctx context.Context, args *BuildArgs, installables ...string) error

func CopyInstallableToCache

func CopyInstallableToCache(
	ctx context.Context,
	out io.Writer,

	to, installable string,
	env []string,
) error

func DaemonVersion

func DaemonVersion(ctx context.Context) (string, error)

DaemonVersion returns the version of the currently running Nix daemon.

func EnsureNixInstalled

func EnsureNixInstalled(ctx context.Context, writer io.Writer, withDaemonFunc func() *bool) (err error)

func EnsureNixpkgsPrefetched

func EnsureNixpkgsPrefetched(w io.Writer, commit string) error

EnsureNixpkgsPrefetched runs the prefetch step to download the flake of the registry

func EnsureValidPlatform

func EnsureValidPlatform(platforms ...string) error

EnsureValidPlatform returns an error if the platform is not supported by nix. https://nixos.org/manual/nix/stable/installation/supported-platforms.html

func Ensured

func Ensured() bool

func Eval

func Eval(path string) ([]byte, error)

Eval is raw nix eval. Needs to be parsed. Useful for stuff like nix eval --raw nixpkgs/9ef09e06806e79e32e30d17aee6879d69c011037#fuse3 to determine if a package if a package can be installed in system.

func EvalPackageName

func EvalPackageName(path string) (string, error)

func ExperimentalFlags

func ExperimentalFlags() []string

func FixInstallableArg

func FixInstallableArg(arg string) string

fixInstallableArg calls fixInstallableArgs with a single argument.

func FixInstallableArgs

func FixInstallableArgs(args []string)

FixInstallableArgs removes the narHash and lastModifiedDate query parameters from any args that are valid installables and the Nix version is <2.25. Otherwise it returns them unchanged.

This fixes an issues with some older versions of Nix where specifying a narHash without a lastModifiedDate results in an error.

func FlakeNixpkgs

func FlakeNixpkgs(commit string) string

FlakeNixpkgs returns a flakes-compatible reference to the nixpkgs registry. TODO savil. Ensure this works with the nixed cache service.

func FlakeUpdate

func FlakeUpdate(ProfileDir string) error

func HashFromNixPkgsURL

func HashFromNixPkgsURL(url string) string

HashFromNixPkgsURL will (for example) return 5233fd2ba76a3accb5aaa999c00509a11fd0793c from github:nixos/nixpkgs/5233fd2ba76a3accb5aaa999c00509a11fd0793c#hello

func IncludeDevboxConfig

func IncludeDevboxConfig(ctx context.Context, username string) error

func IsExitErrorInsecurePackage

func IsExitErrorInsecurePackage(err error, pkgNameOrEmpty, installableOrEmpty string) (bool, error)

func IsGithubNixpkgsURL

func IsGithubNixpkgsURL(url string) bool

IsGithubNixpkgsURL returns true if the package is a flake of the form: github:NixOS/nixpkgs/...

While there are many ways to specify this input, devbox always uses github:NixOS/nixpkgs/<hash> as the URL. If the user wishes to reference nixpkgs themselves, this function may not return true.

func IsInsecureAllowed

func IsInsecureAllowed() bool

func PackageIsInsecure

func PackageIsInsecure(path string) bool

PackageIsInsecure is a fun little nix eval that maybe works.

func PackageKnownVulnerabilities

func PackageKnownVulnerabilities(path string) []string

func PkgExistsForAnySystem

func PkgExistsForAnySystem(pkg string) bool

PkgExistsForAnySystem is a bit slow (~600ms). Only use it if there's already been an error and we want to provide a better error message.

func ProfileBinPath

func ProfileBinPath(projectDir string) string

Warning: be careful using the bins in default/bin, they won't always match bins produced by the flakes.nix. Use devbox.NixBins() instead.

func ProfileInstall

func ProfileInstall(ctx context.Context, args *ProfileInstallArgs) error

func ProfileList

func ProfileList(writer io.Writer, profilePath string, useJSON bool) (string, error)

func ProfileRemove

func ProfileRemove(profilePath string, packageNames ...string) error

ProfileRemove removes packages from a profile. WARNING, don't use indexes, they are not supported by nix 2.20+

func ProfileUpgrade

func ProfileUpgrade(ProfileDir, indexOrName string) error

func RunScript

func RunScript(projectDir, cmdWithArgs string, env map[string]string) error
func Search(url string) (map[string]*PkgInfo, error)

func SearchNixpkgsAttribute

func SearchNixpkgsAttribute(query string) (map[string]*PkgInfo, error)

SearchNixpkgsAttribute is a wrapper around searchSystem that caches results. NOTE: we should be very conservative in where we use this function. `nix search` accepts generalized `installable regex` as arguments but is slow. For certain queries of the form `nixpkgs/<commit-hash>#attribute`, we can know for sure that once `nix search` returns a valid result, it will always be the very same result. Hence we can cache it locally and answer future queries fast, by not calling `nix search`.

func SourceProfile

func SourceProfile() (sourced bool, err error)

func StorePathFromHashPart

func StorePathFromHashPart(ctx context.Context, hash, storeAddr string) (string, error)

func StorePathsAreInStore

func StorePathsAreInStore(ctx context.Context, storePaths []string) (map[string]bool, error)

StorePathsAreInStore a map of store paths to whether they are in the store.

func StorePathsFromInstallable

func StorePathsFromInstallable(ctx context.Context, installable string, allowInsecure bool) ([]string, error)

func System

func System() string

func SystemIsLinux

func SystemIsLinux() bool

func Version

func Version() string

Types

type Args

type Args = nix.Args

type BuildArgs

type BuildArgs struct {
	AllowInsecure     bool
	Env               []string
	ExtraSubstituters []string
	Flags             []string
	Writer            io.Writer
}

type Cmd

type Cmd = nix.Cmd

func Command

func Command(args ...any) *Cmd

type Config

type Config struct {
	ExperimentalFeatures ConfigField[[]string] `json:"experimental-features"`
	Substitute           ConfigField[bool]     `json:"substitute"`
	Substituters         ConfigField[[]string] `json:"substituters"`
	System               ConfigField[string]   `json:"system"`
	TrustedSubstituters  ConfigField[[]string] `json:"trusted-substituters"`
	TrustedUsers         ConfigField[[]string] `json:"trusted-users"`
}

Config is a parsed Nix configuration.

func CurrentConfig

func CurrentConfig(ctx context.Context) (Config, error)

CurrentConfig reads the current Nix configuration.

func (Config) IsUserTrusted

func (c Config) IsUserTrusted(ctx context.Context, username string) (bool, error)

IsUserTrusted reports if the current OS user is in the trusted-users list. If there are any groups in the list, it also checks if the user belongs to any of them.

type ConfigField

type ConfigField[T any] struct {
	Value T `json:"value"`
}

ConfigField is a Nix configuration setting.

type DaemonError

type DaemonError struct {
	// contains filtered or unexported fields
}

DaemonError reports an unsuccessful attempt to connect to the Nix daemon.

func (*DaemonError) Error

func (e *DaemonError) Error() string

func (*DaemonError) Redact

func (e *DaemonError) Redact() string

func (*DaemonError) Unwrap

func (e *DaemonError) Unwrap() error

type FlakeMetadata

type FlakeMetadata struct {
	Description string    `json:"description"`
	Original    flake.Ref `json:"original"`
	Resolved    flake.Ref `json:"resolved"`
	Locked      flake.Ref `json:"locked"`
	Path        string    `json:"path"`
}

func ResolveFlake

func ResolveFlake(ctx context.Context, ref flake.Ref) (FlakeMetadata, error)

type Info

type Info = nix.Info

type Installer

type Installer = nix.Installer

type LegacyPathInfo

type LegacyPathInfo struct {
	Path  string `json:"path"`
	Valid bool   `json:"valid"` // this means path is in store
}

Older nix versions (like 2.17) are an array of objects that contain path and valid fields

type Nix

type Nix = nix.Nix

type NixInstance

type NixInstance struct{}

These make it easier to stub out nix for testing

func (*NixInstance) PrintDevEnv

func (*NixInstance) PrintDevEnv(ctx context.Context, args *PrintDevEnvArgs) (*PrintDevEnvOut, error)

PrintDevEnv calls `nix print-dev-env -f <path>` and returns its output. The output contains all the environment variables and bash functions required to create a nix shell.

type Nixer

type Nixer interface {
	PrintDevEnv(ctx context.Context, args *PrintDevEnvArgs) (*PrintDevEnvOut, error)
}

type PackageInstallWriter

type PackageInstallWriter struct {
	io.Writer
}

func (*PackageInstallWriter) Write

func (fw *PackageInstallWriter) Write(p []byte) (n int, err error)

type PkgInfo

type PkgInfo struct {
	// attribute key is different in flakes vs legacy so we should only use it
	// if we know exactly which version we are using
	AttributeKey string `json:"attribute"`
	PName        string `json:"pname"`
	Summary      string `json:"summary"`
	Version      string `json:"version"`
}

func (*PkgInfo) String

func (i *PkgInfo) String() string

type PrintDevEnvArgs

type PrintDevEnvArgs struct {
	FlakeDir             string
	PrintDevEnvCachePath string
	UsePrintDevEnvCache  bool
}

type PrintDevEnvOut

type PrintDevEnvOut struct {
	Variables map[string]Variable // the key is the name.
}

type ProfileInstallArgs

type ProfileInstallArgs struct {
	Installables []string
	ProfilePath  string
	Writer       io.Writer
}

type StorePathParts

type StorePathParts struct {
	Hash    string
	Name    string
	Version string
	Output  string
}

StorePathParts are the constituent parts of /nix/store/<hash>-<name>-<version>

This is a helper struct for analyzing the string representation

func NewStorePathParts

func NewStorePathParts(path string) StorePathParts

NewStorePathParts splits a Nix store path into its hash, name and version components in the same way that Nix does.

See https://nixos.org/manual/nix/stable/language/builtins.html#builtins-parseDrvName

type Variable

type Variable struct {
	Type  string // valid types are var, exported, and array.
	Value any    // can be a string or an array of strings (iff type is array).
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL