id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
11,143
profiles.hh
NixOS_nix/src/libstore/profiles.hh
#pragma once /** * @file * * Implementation of Profiles. * * See the manual for additional information. */ #include "types.hh" #include "pathlocks.hh" #include <optional> #include <time.h> namespace nix { class StorePath; /** * A positive number identifying a generation for a given profile. * * Generation numbers are assigned sequentially. Each new generation is * assigned 1 + the current highest generation number. */ typedef uint64_t GenerationNumber; /** * A generation is a revision of a profile. * * Each generation is a mapping (key-value pair) from an identifier * (`number`) to a store object (specified by `path`). */ struct Generation { /** * The number of a generation is its unique identifier within the * profile. */ GenerationNumber number; /** * The store path identifies the store object that is the contents * of the generation. * * These store paths / objects are not unique to the generation * within a profile. Nix tries to ensure successive generations have * distinct contents to avoid bloat, but nothing stops two * non-adjacent generations from having the same contents. * * @todo Use `StorePath` instead of `Path`? */ Path path; /** * When the generation was created. This is extra metadata about the * generation used to make garbage collecting old generations more * convenient. */ time_t creationTime; }; /** * All the generations of a profile */ typedef std::list<Generation> Generations; /** * Find all generations for the given profile. * * @param profile A profile specified by its name and location combined * into a path. E.g. if "foo" is the name of the profile, and "/bar/baz" * is the directory it is in, then the path "/bar/baz/foo" would be the * argument for this parameter. * * @return The pair of: * * - The list of currently present generations for the specified profile, * sorted by ascending generation number. * * - The number of the current/active generation. * * Note that the current/active generation need not be the latest one. */ std::pair<Generations, std::optional<GenerationNumber>> findGenerations(Path profile); class LocalFSStore; /** * Create a new generation of the given profile * * If the previous generation (not the currently active one!) has a * distinct store object, a fresh generation number is mapped to the * given store object, referenced by path. Otherwise, the previous * generation is assumed. * * The behavior of reusing existing generations like this makes this * procedure idempotent. It also avoids clutter. */ Path createGeneration(LocalFSStore & store, Path profile, StorePath outPath); /** * Unconditionally delete a generation * * @param profile A profile specified by its name and location combined into a path. * * @param gen The generation number specifying exactly which generation * to delete. * * Because there is no check of whether the generation to delete is * active, this is somewhat unsafe. * * @todo Should we expose this at all? */ void deleteGeneration(const Path & profile, GenerationNumber gen); /** * Delete the given set of generations. * * @param profile The profile, specified by its name and location combined into a path, whose generations we want to delete. * * @param gensToDelete The generations to delete, specified by a set of * numbers. * * @param dryRun Log what would be deleted instead of actually doing * so. * * Trying to delete the currently active generation will fail, and cause * no generations to be deleted. */ void deleteGenerations(const Path & profile, const std::set<GenerationNumber> & gensToDelete, bool dryRun); /** * Delete generations older than `max` passed the current generation. * * @param profile The profile, specified by its name and location combined into a path, whose generations we want to delete. * * @param max How many generations to keep up to the current one. Must * be at least 1 so we don't delete the current one. * * @param dryRun Log what would be deleted instead of actually doing * so. */ void deleteGenerationsGreaterThan(const Path & profile, GenerationNumber max, bool dryRun); /** * Delete all generations other than the current one * * @param profile The profile, specified by its name and location combined into a path, whose generations we want to delete. * * @param dryRun Log what would be deleted instead of actually doing * so. */ void deleteOldGenerations(const Path & profile, bool dryRun); /** * Delete generations older than `t`, except for the most recent one * older than `t`. * * @param profile The profile, specified by its name and location combined into a path, whose generations we want to delete. * * @param dryRun Log what would be deleted instead of actually doing * so. */ void deleteGenerationsOlderThan(const Path & profile, time_t t, bool dryRun); /** * Parse a temp spec intended for `deleteGenerationsOlderThan()`. * * Throws an exception if `timeSpec` fails to parse. */ time_t parseOlderThanTimeSpec(std::string_view timeSpec); /** * Smaller wrapper around `replaceSymlink` for replacing the current * generation of a profile. Does not enforce proper structure. * * @todo Always use `switchGeneration()` instead, and delete this. */ void switchLink(Path link, Path target); /** * Roll back a profile to the specified generation, or to the most * recent one older than the current. */ void switchGeneration( const Path & profile, std::optional<GenerationNumber> dstGen, bool dryRun); /** * Ensure exclusive access to a profile. Any command that modifies * the profile first acquires this lock. */ void lockProfile(PathLocks & lock, const Path & profile); /** * Optimistic locking is used by long-running operations like `nix-env * -i'. Instead of acquiring the exclusive lock for the entire * duration of the operation, we just perform the operation * optimistically (without an exclusive lock), and check at the end * whether the profile changed while we were busy (i.e., the symlink * target changed). If so, the operation is restarted. Restarting is * generally cheap, since the build results are still in the Nix * store. Most of the time, only the user environment has to be * rebuilt. */ std::string optimisticLockProfile(const Path & profile); /** * Create and return the path to a directory suitable for storing the user’s * profiles. */ Path profilesDir(); /** * Return the path to the profile directory for root (but don't try creating it) */ Path rootProfilesDir(); /** * Create and return the path to the file used for storing the users's channels */ Path defaultChannelsDir(); /** * Return the path to the channel directory for root (but don't try creating it) */ Path rootChannelsDir(); /** * Resolve the default profile (~/.nix-profile by default, * $XDG_STATE_HOME/nix/profile if XDG Base Directory Support is enabled), * and create if doesn't exist */ Path getDefaultProfile(); }
7,084
C++
.h
210
31.385714
124
0.745909
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,144
store-api.hh
NixOS_nix/src/libstore/store-api.hh
#pragma once ///@file #include "path.hh" #include "derived-path.hh" #include "hash.hh" #include "content-address.hh" #include "serialise.hh" #include "lru-cache.hh" #include "sync.hh" #include "globals.hh" #include "config.hh" #include "path-info.hh" #include "repair-flag.hh" #include "store-dir-config.hh" #include "store-reference.hh" #include "source-path.hh" #include <nlohmann/json_fwd.hpp> #include <atomic> #include <map> #include <memory> #include <string> #include <chrono> namespace nix { /** * About the class hierarchy of the store types: * * Each store type `Foo` consists of two classes: * * 1. A class `FooConfig : virtual StoreConfig` that contains the configuration * for the store * * It should only contain members of type `const Setting<T>` (or subclasses * of it) and inherit the constructors of `StoreConfig` * (`using StoreConfig::StoreConfig`). * * 2. A class `Foo : virtual Store, virtual FooConfig` that contains the * implementation of the store. * * This class is expected to have a constructor `Foo(const Params & params)` * that calls `StoreConfig(params)` (otherwise you're gonna encounter an * `assertion failure` when trying to instantiate it). * * You can then register the new store using: * * ``` * cpp static RegisterStoreImplementation<Foo, FooConfig> regStore; * ``` */ MakeError(SubstError, Error); /** * denotes a permanent build failure */ MakeError(BuildError, Error); MakeError(InvalidPath, Error); MakeError(Unsupported, Error); MakeError(SubstituteGone, Error); MakeError(SubstituterDisabled, Error); MakeError(InvalidStoreReference, Error); struct Realisation; struct RealisedPath; struct DrvOutput; struct BasicDerivation; struct Derivation; struct SourceAccessor; class NarInfoDiskCache; class Store; typedef std::map<std::string, StorePath> OutputPathMap; enum CheckSigsFlag : bool { NoCheckSigs = false, CheckSigs = true }; enum SubstituteFlag : bool { NoSubstitute = false, Substitute = true }; /** * Magic header of exportPath() output (obsolete). */ const uint32_t exportMagic = 0x4558494e; enum BuildMode : uint8_t { bmNormal, bmRepair, bmCheck }; enum TrustedFlag : bool { NotTrusted = false, Trusted = true }; struct BuildResult; struct KeyedBuildResult; typedef std::map<StorePath, std::optional<ContentAddress>> StorePathCAMap; struct StoreConfig : public StoreDirConfig { using Params = StoreReference::Params; using StoreDirConfig::StoreDirConfig; StoreConfig() = delete; static StringSet getDefaultSystemFeatures(); virtual ~StoreConfig() { } /** * The name of this type of store. */ virtual const std::string name() = 0; /** * Documentation for this type of store. */ virtual std::string doc() { return ""; } /** * An experimental feature this type store is gated, if it is to be * experimental. */ virtual std::optional<ExperimentalFeature> experimentalFeature() const { return std::nullopt; } const Setting<int> pathInfoCacheSize{this, 65536, "path-info-cache-size", "Size of the in-memory store path metadata cache."}; const Setting<bool> isTrusted{this, false, "trusted", R"( Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the [`trusted-public-keys`](@docroot@/command-ref/conf-file.md#conf-trusted-public-keys) setting. )"}; Setting<int> priority{this, 0, "priority", R"( Priority of this store when used as a [substituter](@docroot@/command-ref/conf-file.md#conf-substituters). A lower value means a higher priority. )"}; Setting<bool> wantMassQuery{this, false, "want-mass-query", R"( Whether this store can be queried efficiently for path validity when used as a [substituter](@docroot@/command-ref/conf-file.md#conf-substituters). )"}; Setting<StringSet> systemFeatures{this, getDefaultSystemFeatures(), "system-features", R"( Optional [system features](@docroot@/command-ref/conf-file.md#conf-system-features) available on the system this store uses to build derivations. Example: `"kvm"` )", {}, // Don't document the machine-specific default value false}; }; class Store : public std::enable_shared_from_this<Store>, public virtual StoreConfig { protected: struct PathInfoCacheValue { /** * Time of cache entry creation or update */ std::chrono::time_point<std::chrono::steady_clock> time_point = std::chrono::steady_clock::now(); /** * Null if missing */ std::shared_ptr<const ValidPathInfo> value; /** * Whether the value is valid as a cache entry. The path may not * exist. */ bool isKnownNow(); /** * Past tense, because a path can only be assumed to exists when * isKnownNow() && didExist() */ inline bool didExist() { return value != nullptr; } }; struct State { LRUCache<std::string, PathInfoCacheValue> pathInfoCache; }; SharedSync<State> state; std::shared_ptr<NarInfoDiskCache> diskCache; Store(const Params & params); public: /** * Perform any necessary effectful operation to make the store up and * running */ virtual void init() {}; virtual ~Store() { } /** * @todo move to `StoreConfig` one we store enough information in * those to recover the scheme and authority in all cases. */ virtual std::string getUri() = 0; /** * Follow symlinks until we end up with a path in the Nix store. */ Path followLinksToStore(std::string_view path) const; /** * Same as followLinksToStore(), but apply toStorePath() to the * result. */ StorePath followLinksToStorePath(std::string_view path) const; /** * Check whether a path is valid. */ bool isValidPath(const StorePath & path); protected: virtual bool isValidPathUncached(const StorePath & path); public: /** * If requested, substitute missing paths. This * implements nix-copy-closure's --use-substitutes * flag. */ void substitutePaths(const StorePathSet & paths); /** * Query which of the given paths is valid. Optionally, try to * substitute missing paths. */ virtual StorePathSet queryValidPaths(const StorePathSet & paths, SubstituteFlag maybeSubstitute = NoSubstitute); /** * Query the set of all valid paths. Note that for some store * backends, the name part of store paths may be replaced by `x` * (i.e. you'll get `/nix/store/<hash>-x` rather than * `/nix/store/<hash>-<name>`). Use queryPathInfo() to obtain the * full store path. FIXME: should return a set of * `std::variant<StorePath, HashPart>` to get rid of this hack. */ virtual StorePathSet queryAllValidPaths() { unsupported("queryAllValidPaths"); } constexpr static const char * MissingName = "x"; /** * Query information about a valid path. It is permitted to omit * the name part of the store path. */ ref<const ValidPathInfo> queryPathInfo(const StorePath & path); /** * Asynchronous version of queryPathInfo(). */ void queryPathInfo(const StorePath & path, Callback<ref<const ValidPathInfo>> callback) noexcept; /** * Version of queryPathInfo() that only queries the local narinfo cache and not * the actual store. * * @return `std::nullopt` if nothing is known about the path in the local narinfo cache. * @return `std::make_optional(nullptr)` if the path is known to not exist. * @return `std::make_optional(validPathInfo)` if the path is known to exist. */ std::optional<std::shared_ptr<const ValidPathInfo>> queryPathInfoFromClientCache(const StorePath & path); /** * Query the information about a realisation. */ std::shared_ptr<const Realisation> queryRealisation(const DrvOutput &); /** * Asynchronous version of queryRealisation(). */ void queryRealisation(const DrvOutput &, Callback<std::shared_ptr<const Realisation>> callback) noexcept; /** * Check whether the given valid path info is sufficiently attested, by * either being signed by a trusted public key or content-addressed, in * order to be included in the given store. * * These same checks would be performed in addToStore, but this allows an * earlier failure in the case where dependencies need to be added too, but * the addToStore wouldn't fail until those dependencies are added. Also, * we don't really want to add the dependencies listed in a nar info we * don't trust anyyways. */ virtual bool pathInfoIsUntrusted(const ValidPathInfo &) { return true; } virtual bool realisationIsUntrusted(const Realisation & ) { return true; } protected: virtual void queryPathInfoUncached(const StorePath & path, Callback<std::shared_ptr<const ValidPathInfo>> callback) noexcept = 0; virtual void queryRealisationUncached(const DrvOutput &, Callback<std::shared_ptr<const Realisation>> callback) noexcept = 0; public: /** * Queries the set of incoming FS references for a store path. * The result is not cleared. */ virtual void queryReferrers(const StorePath & path, StorePathSet & referrers) { unsupported("queryReferrers"); } /** * @return all currently valid derivations that have `path` as an * output. * * (Note that the result of `queryDeriver()` is the derivation that * was actually used to produce `path`, which may not exist * anymore.) */ virtual StorePathSet queryValidDerivers(const StorePath & path) { return {}; }; /** * Query the outputs of the derivation denoted by `path`. */ virtual StorePathSet queryDerivationOutputs(const StorePath & path); /** * Query the mapping outputName => outputPath for the given * derivation. All outputs are mentioned so ones mising the mapping * are mapped to `std::nullopt`. */ virtual std::map<std::string, std::optional<StorePath>> queryPartialDerivationOutputMap( const StorePath & path, Store * evalStore = nullptr); /** * Like `queryPartialDerivationOutputMap` but only considers * statically known output paths (i.e. those that can be gotten from * the derivation itself. * * Just a helper function for implementing * `queryPartialDerivationOutputMap`. */ virtual std::map<std::string, std::optional<StorePath>> queryStaticPartialDerivationOutputMap( const StorePath & path); /** * Query the mapping outputName=>outputPath for the given derivation. * Assume every output has a mapping and throw an exception otherwise. */ OutputPathMap queryDerivationOutputMap(const StorePath & path, Store * evalStore = nullptr); /** * Query the full store path given the hash part of a valid store * path, or empty if the path doesn't exist. */ virtual std::optional<StorePath> queryPathFromHashPart(const std::string & hashPart) = 0; /** * Query which of the given paths have substitutes. */ virtual StorePathSet querySubstitutablePaths(const StorePathSet & paths) { return {}; }; /** * Query substitute info (i.e. references, derivers and download * sizes) of a map of paths to their optional ca values. The info of * the first succeeding substituter for each path will be returned. * If a path does not have substitute info, it's omitted from the * resulting ‘infos’ map. */ virtual void querySubstitutablePathInfos(const StorePathCAMap & paths, SubstitutablePathInfos & infos); /** * Import a path into the store. */ virtual void addToStore(const ValidPathInfo & info, Source & narSource, RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs) = 0; /** * A list of paths infos along with a source providing the content * of the associated store path */ using PathsSource = std::vector<std::pair<ValidPathInfo, std::unique_ptr<Source>>>; /** * Import multiple paths into the store. */ virtual void addMultipleToStore( Source & source, RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs); virtual void addMultipleToStore( PathsSource & pathsToCopy, Activity & act, RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs); /** * Copy the contents of a path to the store and register the * validity the resulting path. * * @return The resulting path is returned. * @param filter This function can be used to exclude files (see * libutil/archive.hh). */ virtual StorePath addToStore( std::string_view name, const SourcePath & path, ContentAddressMethod method = ContentAddressMethod::Raw::NixArchive, HashAlgorithm hashAlgo = HashAlgorithm::SHA256, const StorePathSet & references = StorePathSet(), PathFilter & filter = defaultPathFilter, RepairFlag repair = NoRepair); /** * Copy the contents of a path to the store and register the * validity the resulting path, using a constant amount of * memory. */ ValidPathInfo addToStoreSlow( std::string_view name, const SourcePath & path, ContentAddressMethod method = ContentAddressMethod::Raw::NixArchive, HashAlgorithm hashAlgo = HashAlgorithm::SHA256, const StorePathSet & references = StorePathSet(), std::optional<Hash> expectedCAHash = {}); /** * Like addToStore(), but the contents of the path are contained * in `dump`, which is either a NAR serialisation (if recursive == * true) or simply the contents of a regular file (if recursive == * false). * * `dump` may be drained. * * @param dumpMethod What serialisation format is `dump`, i.e. how * to deserialize it. Must either match hashMethod or be * `FileSerialisationMethod::NixArchive`. * * @param hashMethod How content addressing? Need not match be the * same as `dumpMethod`. * * @todo remove? */ virtual StorePath addToStoreFromDump( Source & dump, std::string_view name, FileSerialisationMethod dumpMethod = FileSerialisationMethod::NixArchive, ContentAddressMethod hashMethod = ContentAddressMethod::Raw::NixArchive, HashAlgorithm hashAlgo = HashAlgorithm::SHA256, const StorePathSet & references = StorePathSet(), RepairFlag repair = NoRepair) = 0; /** * Add a mapping indicating that `deriver!outputName` maps to the output path * `output`. * * This is redundant for known-input-addressed and fixed-output derivations * as this information is already present in the drv file, but necessary for * floating-ca derivations and their dependencies as there's no way to * retrieve this information otherwise. */ virtual void registerDrvOutput(const Realisation & output) { unsupported("registerDrvOutput"); } virtual void registerDrvOutput(const Realisation & output, CheckSigsFlag checkSigs) { return registerDrvOutput(output); } /** * Write a NAR dump of a store path. */ virtual void narFromPath(const StorePath & path, Sink & sink) = 0; /** * For each path, if it's a derivation, build it. Building a * derivation means ensuring that the output paths are valid. If * they are already valid, this is a no-op. Otherwise, validity * can be reached in two ways. First, if the output paths is * substitutable, then build the path that way. Second, the * output paths can be created by running the builder, after * recursively building any sub-derivations. For inputs that are * not derivations, substitute them. */ virtual void buildPaths( const std::vector<DerivedPath> & paths, BuildMode buildMode = bmNormal, std::shared_ptr<Store> evalStore = nullptr); /** * Like buildPaths(), but return a vector of \ref BuildResult * BuildResults corresponding to each element in paths. Note that in * case of a build/substitution error, this function won't throw an * exception, but return a BuildResult containing an error message. */ virtual std::vector<KeyedBuildResult> buildPathsWithResults( const std::vector<DerivedPath> & paths, BuildMode buildMode = bmNormal, std::shared_ptr<Store> evalStore = nullptr); /** * Build a single non-materialized derivation (i.e. not from an * on-disk .drv file). * * @param drvPath This is used to deduplicate worker goals so it is * imperative that is correct. That said, it doesn't literally need * to be store path that would be calculated from writing this * derivation to the store: it is OK if it instead is that of a * Derivation which would resolve to this (by taking the outputs of * it's input derivations and adding them as input sources) such * that the build time referenceable-paths are the same. * * In the input-addressed case, we usually *do* use an "original" * unresolved derivations's path, as that is what will be used in the * buildPaths case. Also, the input-addressed output paths are verified * only by that contents of that specific unresolved derivation, so it is * nice to keep that information around so if the original derivation is * ever obtained later, it can be verified whether the trusted user in fact * used the proper output path. * * In the content-addressed case, we want to always use the resolved * drv path calculated from the provided derivation. This serves two * purposes: * * - It keeps the operation trustless, by ruling out a maliciously * invalid drv path corresponding to a non-resolution-equivalent * derivation. * * - For the floating case in particular, it ensures that the derivation * to output mapping respects the resolution equivalence relation, so * one cannot choose different resolution-equivalent derivations to * subvert dependency coherence (i.e. the property that one doesn't end * up with multiple different versions of dependencies without * explicitly choosing to allow it). */ virtual BuildResult buildDerivation(const StorePath & drvPath, const BasicDerivation & drv, BuildMode buildMode = bmNormal); /** * Ensure that a path is valid. If it is not currently valid, it * may be made valid by running a substitute (if defined for the * path). */ virtual void ensurePath(const StorePath & path); /** * Add a store path as a temporary root of the garbage collector. * The root disappears as soon as we exit. */ virtual void addTempRoot(const StorePath & path) { debug("not creating temporary root, store doesn't support GC"); } /** * @return a string representing information about the path that * can be loaded into the database using `nix-store --load-db` or * `nix-store --register-validity`. */ std::string makeValidityRegistration(const StorePathSet & paths, bool showDerivers, bool showHash); /** * Optimise the disk space usage of the Nix store by hard-linking files * with the same contents. */ virtual void optimiseStore() { }; /** * Check the integrity of the Nix store. * * @return true if errors remain. */ virtual bool verifyStore(bool checkContents, RepairFlag repair = NoRepair) { return false; }; /** * @return An object to access files in the Nix store. */ virtual ref<SourceAccessor> getFSAccessor(bool requireValidPath = true) = 0; /** * Repair the contents of the given path by redownloading it using * a substituter (if available). */ virtual void repairPath(const StorePath & path); /** * Add signatures to the specified store path. The signatures are * not verified. */ virtual void addSignatures(const StorePath & storePath, const StringSet & sigs) { unsupported("addSignatures"); } /* Utility functions. */ /** * Read a derivation, after ensuring its existence through * ensurePath(). */ Derivation derivationFromPath(const StorePath & drvPath); /** * Read a derivation (which must already be valid). */ Derivation readDerivation(const StorePath & drvPath); /** * Read a derivation from a potentially invalid path. */ Derivation readInvalidDerivation(const StorePath & drvPath); /** * @param [out] out Place in here the set of all store paths in the * file system closure of `storePath`; that is, all paths than can * be directly or indirectly reached from it. `out` is not cleared. * * @param flipDirection If true, the set of paths that can reach * `storePath` is returned; that is, the closures under the * `referrers` relation instead of the `references` relation is * returned. */ virtual void computeFSClosure(const StorePathSet & paths, StorePathSet & out, bool flipDirection = false, bool includeOutputs = false, bool includeDerivers = false); void computeFSClosure(const StorePath & path, StorePathSet & out, bool flipDirection = false, bool includeOutputs = false, bool includeDerivers = false); /** * Given a set of paths that are to be built, return the set of * derivations that will be built, and the set of output paths that * will be substituted. */ virtual void queryMissing(const std::vector<DerivedPath> & targets, StorePathSet & willBuild, StorePathSet & willSubstitute, StorePathSet & unknown, uint64_t & downloadSize, uint64_t & narSize); /** * Sort a set of paths topologically under the references * relation. If p refers to q, then p precedes q in this list. */ StorePaths topoSortPaths(const StorePathSet & paths); /** * Export multiple paths in the format expected by ‘nix-store * --import’. */ void exportPaths(const StorePathSet & paths, Sink & sink); void exportPath(const StorePath & path, Sink & sink); /** * Import a sequence of NAR dumps created by exportPaths() into the * Nix store. Optionally, the contents of the NARs are preloaded * into the specified FS accessor to speed up subsequent access. */ StorePaths importPaths(Source & source, CheckSigsFlag checkSigs = CheckSigs); struct Stats { std::atomic<uint64_t> narInfoRead{0}; std::atomic<uint64_t> narInfoReadAverted{0}; std::atomic<uint64_t> narInfoMissing{0}; std::atomic<uint64_t> narInfoWrite{0}; std::atomic<uint64_t> pathInfoCacheSize{0}; std::atomic<uint64_t> narRead{0}; std::atomic<uint64_t> narReadBytes{0}; std::atomic<uint64_t> narReadCompressedBytes{0}; std::atomic<uint64_t> narWrite{0}; std::atomic<uint64_t> narWriteAverted{0}; std::atomic<uint64_t> narWriteBytes{0}; std::atomic<uint64_t> narWriteCompressedBytes{0}; std::atomic<uint64_t> narWriteCompressionTimeMs{0}; }; const Stats & getStats(); /** * Computes the full closure of of a set of store-paths for e.g. * derivations that need this information for `exportReferencesGraph`. */ StorePathSet exportReferences(const StorePathSet & storePaths, const StorePathSet & inputPaths); /** * Given a store path, return the realisation actually used in the realisation of this path: * - If the path is a content-addressed derivation, try to resolve it * - Otherwise, find one of its derivers */ std::optional<StorePath> getBuildDerivationPath(const StorePath &); /** * Hack to allow long-running processes like hydra-queue-runner to * occasionally flush their path info cache. */ void clearPathInfoCache() { state.lock()->pathInfoCache.clear(); } /** * Establish a connection to the store, for store types that have * a notion of connection. Otherwise this is a no-op. */ virtual void connect() { }; /** * Get the protocol version of this store or it's connection. */ virtual unsigned int getProtocol() { return 0; }; /** * @return/ whether store trusts *us*. * * `std::nullopt` means we do not know. * * @note This is the opposite of the StoreConfig::isTrusted * store setting. That is about whether *we* trust the store. */ virtual std::optional<TrustedFlag> isTrustedClient() = 0; virtual Path toRealPath(const Path & storePath) { return storePath; } Path toRealPath(const StorePath & storePath) { return toRealPath(printStorePath(storePath)); } /** * Synchronises the options of the client with those of the daemon * (a no-op when there’s no daemon) */ virtual void setOptions() { } virtual std::optional<std::string> getVersion() { return {}; } protected: Stats stats; /** * Helper for methods that are not unsupported: this is used for * default definitions for virtual methods that are meant to be overriden. * * @todo Using this should be a last resort. It is better to make * the method "virtual pure" and/or move it to a subclass. */ [[noreturn]] void unsupported(const std::string & op) { throw Unsupported("operation '%s' is not supported by store '%s'", op, getUri()); } }; /** * Copy a path from one store to another. */ void copyStorePath( Store & srcStore, Store & dstStore, const StorePath & storePath, RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs); /** * Copy store paths from one store to another. The paths may be copied * in parallel. They are copied in a topologically sorted order (i.e. if * A is a reference of B, then A is copied before B), but the set of * store paths is not automatically closed; use copyClosure() for that. * * @return a map of what each path was copied to the dstStore as. */ std::map<StorePath, StorePath> copyPaths( Store & srcStore, Store & dstStore, const std::set<RealisedPath> &, RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs, SubstituteFlag substitute = NoSubstitute); std::map<StorePath, StorePath> copyPaths( Store & srcStore, Store & dstStore, const StorePathSet & paths, RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs, SubstituteFlag substitute = NoSubstitute); /** * Copy the closure of `paths` from `srcStore` to `dstStore`. */ void copyClosure( Store & srcStore, Store & dstStore, const std::set<RealisedPath> & paths, RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs, SubstituteFlag substitute = NoSubstitute); void copyClosure( Store & srcStore, Store & dstStore, const StorePathSet & paths, RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs, SubstituteFlag substitute = NoSubstitute); /** * Remove the temporary roots file for this process. Any temporary * root becomes garbage after this point unless it has been registered * as a (permanent) root. */ void removeTempRoots(); /** * Resolve the derived path completely, failing if any derivation output * is unknown. */ StorePath resolveDerivedPath(Store &, const SingleDerivedPath &, Store * evalStore = nullptr); OutputPathMap resolveDerivedPath(Store &, const DerivedPath::Built &, Store * evalStore = nullptr); /** * @return a Store object to access the Nix store denoted by * ‘uri’ (slight misnomer...). */ ref<Store> openStore(StoreReference && storeURI); /** * Opens the store at `uri`, where `uri` is in the format expected by `StoreReference::parse` */ ref<Store> openStore(const std::string & uri = settings.storeUri.get(), const Store::Params & extraParams = Store::Params()); /** * @return the default substituter stores, defined by the * ‘substituters’ option and various legacy options. */ std::list<ref<Store>> getDefaultSubstituters(); struct StoreFactory { std::set<std::string> uriSchemes; /** * The `authorityPath` parameter is `<authority>/<path>`, or really * whatever comes after `<scheme>://` and before `?<query-params>`. */ std::function<std::shared_ptr<Store> ( std::string_view scheme, std::string_view authorityPath, const Store::Params & params)> create; std::function<std::shared_ptr<StoreConfig> ()> getConfig; }; struct Implementations { static std::vector<StoreFactory> * registered; template<typename T, typename TConfig> static void add() { if (!registered) registered = new std::vector<StoreFactory>(); StoreFactory factory{ .uriSchemes = TConfig::uriSchemes(), .create = ([](auto scheme, auto uri, auto & params) -> std::shared_ptr<Store> { return std::make_shared<T>(scheme, uri, params); }), .getConfig = ([]() -> std::shared_ptr<StoreConfig> { return std::make_shared<TConfig>(StringMap({})); }) }; registered->push_back(factory); } }; template<typename T, typename TConfig> struct RegisterStoreImplementation { RegisterStoreImplementation() { Implementations::add<T, TConfig>(); } }; /** * Display a set of paths in human-readable form (i.e., between quotes * and separated by commas). */ std::string showPaths(const PathSet & paths); std::optional<ValidPathInfo> decodeValidPathInfo( const Store & store, std::istream & str, std::optional<HashResult> hashGiven = std::nullopt); const ContentAddress * getDerivationCA(const BasicDerivation & drv); std::map<DrvOutput, StorePath> drvOutputReferences( Store & store, const Derivation & drv, const StorePath & outputPath, Store * evalStore = nullptr); }
30,794
C++
.h
795
33.089308
157
0.683251
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,145
ssh.hh
NixOS_nix/src/libstore/ssh.hh
#pragma once ///@file #include "sync.hh" #include "processes.hh" #include "file-system.hh" namespace nix { class SSHMaster { private: const std::string host; bool fakeSSH; const std::string keyFile; /** * Raw bytes, not Base64 encoding. */ const std::string sshPublicHostKey; const bool useMaster; const bool compress; const Descriptor logFD; struct State { #ifndef _WIN32 // TODO re-enable on Windows, once we can start processes. Pid sshMaster; #endif std::unique_ptr<AutoDelete> tmpDir; Path socketPath; }; Sync<State> state_; void addCommonSSHOpts(Strings & args); bool isMasterRunning(); #ifndef _WIN32 // TODO re-enable on Windows, once we can start processes. Path startMaster(); #endif public: SSHMaster( std::string_view host, std::string_view keyFile, std::string_view sshPublicHostKey, bool useMaster, bool compress, Descriptor logFD = INVALID_DESCRIPTOR); struct Connection { #ifndef _WIN32 // TODO re-enable on Windows, once we can start processes. Pid sshPid; #endif AutoCloseFD out, in; }; /** * @param command The command (arg vector) to execute. * * @param extraSshArgs Extra arguments to pass to SSH (not the command to * execute). Will not be used when "fake SSHing" to the local * machine. */ std::unique_ptr<Connection> startCommand( Strings && command, Strings && extraSshArgs = {}); }; }
1,536
C++
.h
58
21.603448
78
0.665529
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,146
fchmodat2-compat.hh
NixOS_nix/src/libstore/linux/fchmodat2-compat.hh
/* * Determine the syscall number for `fchmodat2`. * * On most platforms this is 452. Exceptions can be found on * a glibc git checkout via `rg --pcre2 'define __NR_fchmodat2 (?!452)'`. * * The problem is that glibc 2.39 and libseccomp 2.5.5 are needed to * get the syscall number. However, a Nix built against nixpkgs 23.11 * (glibc 2.38) should still have the issue fixed without depending * on the build environment. * * To achieve that, the macros below try to determine the platform and * set the syscall number which is platform-specific, but * in most cases 452. * * TODO: remove this when 23.11 is EOL and the entire (supported) ecosystem * is on glibc 2.39. */ #if HAVE_SECCOMP # if defined(__alpha__) # define NIX_SYSCALL_FCHMODAT2 562 # elif defined(__x86_64__) && SIZE_MAX == 0xFFFFFFFF // x32 # define NIX_SYSCALL_FCHMODAT2 1073742276 # elif defined(__mips__) && defined(__mips64) && defined(_ABIN64) // mips64/n64 # define NIX_SYSCALL_FCHMODAT2 5452 # elif defined(__mips__) && defined(__mips64) && defined(_ABIN32) // mips64/n32 # define NIX_SYSCALL_FCHMODAT2 6452 # elif defined(__mips__) && defined(_ABIO32) // mips32 # define NIX_SYSCALL_FCHMODAT2 4452 # else # define NIX_SYSCALL_FCHMODAT2 452 # endif #endif // HAVE_SECCOMP
1,287
C++
.h
33
37.454545
80
0.710295
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,147
personality.hh
NixOS_nix/src/libstore/linux/personality.hh
#pragma once ///@file #include <string> namespace nix::linux { void setPersonality(std::string_view system); }
117
C++
.h
6
17.5
45
0.771429
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,148
buildenv.hh
NixOS_nix/src/libstore/builtins/buildenv.hh
#pragma once ///@file #include "store-api.hh" namespace nix { /** * Think of this as a "store level package attrset", but stripped down to no more than the needs of buildenv. */ struct Package { Path path; bool active; int priority; Package(const Path & path, bool active, int priority) : path{path}, active{active}, priority{priority} {} }; class BuildEnvFileConflictError : public Error { public: const Path fileA; const Path fileB; int priority; BuildEnvFileConflictError( const Path fileA, const Path fileB, int priority ) : Error( "Unable to build profile. There is a conflict for the following files:\n" "\n" " %1%\n" " %2%", fileA, fileB ) , fileA(fileA) , fileB(fileB) , priority(priority) {} }; typedef std::vector<Package> Packages; void buildProfile(const Path & out, Packages && pkgs); void builtinBuildenv( const BasicDerivation & drv, const std::map<std::string, Path> & outputs); }
1,094
C++
.h
43
19.906977
109
0.62476
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,149
user-lock.hh
NixOS_nix/src/libstore/unix/user-lock.hh
#pragma once ///@file #include <memory> #include <vector> #include <sys/types.h> namespace nix { struct UserLock { virtual ~UserLock() { } /** * Get the first and last UID. */ std::pair<uid_t, uid_t> getUIDRange() { auto first = getUID(); return {first, first + getUIDCount() - 1}; } /** * Get the first UID. */ virtual uid_t getUID() = 0; virtual uid_t getUIDCount() = 0; virtual gid_t getGID() = 0; virtual std::vector<gid_t> getSupplementaryGIDs() = 0; }; /** * Acquire a user lock for a UID range of size `nrIds`. Note that this * may return nullptr if no user is available. */ std::unique_ptr<UserLock> acquireUserLock(uid_t nrIds, bool useUserNamespace); bool useBuildUsers(); }
775
C++
.h
32
20.40625
78
0.639344
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,150
child.hh
NixOS_nix/src/libstore/unix/build/child.hh
#pragma once ///@file namespace nix { /** * Common initialisation performed in child processes. */ void commonChildInit(); }
130
C++
.h
8
14.625
54
0.756303
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,151
local-derivation-goal.hh
NixOS_nix/src/libstore/unix/build/local-derivation-goal.hh
#pragma once ///@file #include "derivation-goal.hh" #include "local-store.hh" #include "processes.hh" namespace nix { struct LocalDerivationGoal : public DerivationGoal { LocalStore & getLocalStore(); /** * User selected for running the builder. */ std::unique_ptr<UserLock> buildUser; /** * The process ID of the builder. */ Pid pid; /** * The cgroup of the builder, if any. */ std::optional<Path> cgroup; /** * The temporary directory used for the build. */ Path tmpDir; /** * The top-level temporary directory. `tmpDir` is either equal to * or a child of this directory. */ Path topTmpDir; /** * The path of the temporary directory in the sandbox. */ Path tmpDirInSandbox; /** * Master side of the pseudoterminal used for the builder's * standard output/error. */ AutoCloseFD builderOut; /** * Pipe for synchronising updates to the builder namespaces. */ Pipe userNamespaceSync; /** * The mount namespace and user namespace of the builder, used to add additional * paths to the sandbox as a result of recursive Nix calls. */ AutoCloseFD sandboxMountNamespace; AutoCloseFD sandboxUserNamespace; /** * On Linux, whether we're doing the build in its own user * namespace. */ bool usingUserNamespace = true; /** * Whether we're currently doing a chroot build. */ bool useChroot = false; /** * The parent directory of `chrootRootDir`. It has permission 700 * and is owned by root to ensure other users cannot mess with * `chrootRootDir`. */ Path chrootParentDir; /** * The root of the chroot environment. */ Path chrootRootDir; /** * RAII object to delete the chroot directory. */ std::shared_ptr<AutoDelete> autoDelChroot; /** * Whether to run the build in a private network namespace. */ bool privateNetwork = false; /** * Stuff we need to pass to initChild(). */ struct ChrootPath { Path source; bool optional; ChrootPath(Path source = "", bool optional = false) : source(source), optional(optional) { } }; typedef map<Path, ChrootPath> PathsInChroot; // maps target path to source path PathsInChroot pathsInChroot; typedef map<std::string, std::string> Environment; Environment env; #if __APPLE__ typedef std::string SandboxProfile; SandboxProfile additionalSandboxProfile; #endif /** * Hash rewriting. */ StringMap inputRewrites, outputRewrites; typedef map<StorePath, StorePath> RedirectedOutputs; RedirectedOutputs redirectedOutputs; /** * The output paths used during the build. * * - Input-addressed derivations or fixed content-addressed outputs are * sometimes built when some of their outputs already exist, and can not * be hidden via sandboxing. We use temporary locations instead and * rewrite after the build. Otherwise the regular predetermined paths are * put here. * * - Floating content-addressed derivations do not know their final build * output paths until the outputs are hashed, so random locations are * used, and then renamed. The randomness helps guard against hidden * self-references. */ OutputPathMap scratchOutputs; uid_t sandboxUid() { return usingUserNamespace ? (!buildUser || buildUser->getUIDCount() == 1 ? 1000 : 0) : buildUser->getUID(); } gid_t sandboxGid() { return usingUserNamespace ? (!buildUser || buildUser->getUIDCount() == 1 ? 100 : 0) : buildUser->getGID(); } const static Path homeDir; /** * The recursive Nix daemon socket. */ AutoCloseFD daemonSocket; /** * The daemon main thread. */ std::thread daemonThread; /** * The daemon worker threads. */ std::vector<std::thread> daemonWorkerThreads; /** * Paths that were added via recursive Nix calls. */ StorePathSet addedPaths; /** * Realisations that were added via recursive Nix calls. */ std::set<DrvOutput> addedDrvOutputs; /** * Recursive Nix calls are only allowed to build or realize paths * in the original input closure or added via a recursive Nix call * (so e.g. you can't do 'nix-store -r /nix/store/<bla>' where * /nix/store/<bla> is some arbitrary path in a binary cache). */ bool isAllowed(const StorePath & path) { return inputPaths.count(path) || addedPaths.count(path); } bool isAllowed(const DrvOutput & id) { return addedDrvOutputs.count(id); } bool isAllowed(const DerivedPath & req); friend struct RestrictedStore; using DerivationGoal::DerivationGoal; virtual ~LocalDerivationGoal() override; /** * Whether we need to perform hash rewriting if there are valid output paths. */ bool needsHashRewrite(); /** * The additional states. */ Goal::Co tryLocalBuild() override; /** * Start building a derivation. */ void startBuilder(); /** * Fill in the environment for the builder. */ void initEnv(); /** * Process messages send by the sandbox initialization. */ void processSandboxSetupMessages(); /** * Setup tmp dir location. */ void initTmpDir(); /** * Write a JSON file containing the derivation attributes. */ void writeStructuredAttrs(); /** * Start an in-process nix daemon thread for recursive-nix. */ void startDaemon(); /** * Stop the in-process nix daemon thread. * @see startDaemon */ void stopDaemon(); /** * Add 'path' to the set of paths that may be referenced by the * outputs, and make it appear in the sandbox. */ void addDependency(const StorePath & path); /** * Make a file owned by the builder. */ void chownToBuilder(const Path & path); int getChildStatus() override; /** * Run the builder's process. */ void runChild(); /** * Check that the derivation outputs all exist and register them * as valid. */ SingleDrvOutputs registerOutputs() override; void signRealisation(Realisation &) override; /** * Check that an output meets the requirements specified by the * 'outputChecks' attribute (or the legacy * '{allowed,disallowed}{References,Requisites}' attributes). */ void checkOutputs(const std::map<std::string, ValidPathInfo> & outputs); /** * Close the read side of the logger pipe. */ void closeReadPipes() override; /** * Cleanup hooks for buildDone() */ void cleanupHookFinally() override; void cleanupPreChildKill() override; void cleanupPostChildKill() override; bool cleanupDecideWhetherDiskFull() override; void cleanupPostOutputsRegisteredModeCheck() override; void cleanupPostOutputsRegisteredModeNonCheck() override; bool isReadDesc(int fd) override; /** * Delete the temporary directory, if we have one. */ void deleteTmpDir(bool force); /** * Forcibly kill the child process, if any. * * Called by destructor, can't be overridden */ void killChild() override final; /** * Kill any processes running under the build user UID or in the * cgroup of the build. */ void killSandbox(bool getStats); /** * Create alternative path calculated from but distinct from the * input, so we can avoid overwriting outputs (or other store paths) * that already exist. */ StorePath makeFallbackPath(const StorePath & path); /** * Make a path to another based on the output name along with the * derivation hash. * * @todo Add option to randomize, so we can audit whether our * rewrites caught everything */ StorePath makeFallbackPath(OutputNameView outputName); }; }
8,139
C++
.h
264
25.193182
134
0.658605
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,152
hook-instance.hh
NixOS_nix/src/libstore/unix/build/hook-instance.hh
#pragma once ///@file #include "logging.hh" #include "serialise.hh" #include "processes.hh" namespace nix { struct HookInstance { /** * Pipes for talking to the build hook. */ Pipe toHook; /** * Pipe for the hook's standard output/error. */ Pipe fromHook; /** * Pipe for the builder's standard output/error. */ Pipe builderOut; /** * The process ID of the hook. */ Pid pid; FdSink sink; std::map<ActivityId, Activity> activities; HookInstance(); ~HookInstance(); }; }
567
C++
.h
30
14.6
52
0.621673
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,153
substitution-goal.hh
NixOS_nix/src/libstore/build/substitution-goal.hh
#pragma once ///@file #include "worker.hh" #include "store-api.hh" #include "goal.hh" #include "muxable-pipe.hh" #include <coroutine> #include <future> #include <source_location> namespace nix { struct PathSubstitutionGoal : public Goal { /** * The store path that should be realised through a substitute. */ StorePath storePath; /** * Whether to try to repair a valid path. */ RepairFlag repair; /** * Pipe for the substituter's standard output. */ MuxablePipe outPipe; /** * The substituter thread. */ std::thread thr; std::unique_ptr<MaintainCount<uint64_t>> maintainExpectedSubstitutions, maintainRunningSubstitutions, maintainExpectedNar, maintainExpectedDownload; /** * Content address for recomputing store path */ std::optional<ContentAddress> ca; Done done( ExitCode result, BuildResult::Status status, std::optional<std::string> errorMsg = {}); public: PathSubstitutionGoal(const StorePath & storePath, Worker & worker, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt); ~PathSubstitutionGoal(); void timedOut(Error && ex) override { unreachable(); }; /** * We prepend "a$" to the key name to ensure substitution goals * happen before derivation goals. */ std::string key() override { return "a$" + std::string(storePath.name()) + "$" + worker.store.printStorePath(storePath); } /** * The states. */ Co init() override; Co gotInfo(); Co tryToRun(StorePath subPath, nix::ref<Store> sub, std::shared_ptr<const ValidPathInfo> info, bool & substituterFailed); Co finished(); /** * Callback used by the worker to write to the log. */ void handleChildOutput(Descriptor fd, std::string_view data) override {}; void handleEOF(Descriptor fd) override; /* Called by destructor, can't be overridden */ void cleanup() override final; JobCategory jobCategory() const override { return JobCategory::Substitution; }; }; }
2,120
C++
.h
69
25.753623
150
0.674041
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,154
drv-output-substitution-goal.hh
NixOS_nix/src/libstore/build/drv-output-substitution-goal.hh
#pragma once ///@file #include <thread> #include <future> #include "store-api.hh" #include "goal.hh" #include "realisation.hh" #include "muxable-pipe.hh" namespace nix { class Worker; /** * Substitution of a derivation output. * This is done in three steps: * 1. Fetch the output info from a substituter * 2. Substitute the corresponding output path * 3. Register the output info */ class DrvOutputSubstitutionGoal : public Goal { /** * The drv output we're trying to substitute */ DrvOutput id; public: DrvOutputSubstitutionGoal(const DrvOutput& id, Worker & worker, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt); typedef void (DrvOutputSubstitutionGoal::*GoalState)(); GoalState state; Co init() override; Co realisationFetched(std::shared_ptr<const Realisation> outputInfo, nix::ref<nix::Store> sub); void timedOut(Error && ex) override { unreachable(); }; std::string key() override; void handleEOF(Descriptor fd) override; JobCategory jobCategory() const override { return JobCategory::Substitution; }; }; }
1,132
C++
.h
36
28.055556
147
0.728281
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,155
derivation-goal.hh
NixOS_nix/src/libstore/build/derivation-goal.hh
#pragma once ///@file #include "parsed-derivations.hh" #ifndef _WIN32 # include "user-lock.hh" #endif #include "outputs-spec.hh" #include "store-api.hh" #include "pathlocks.hh" #include "goal.hh" namespace nix { using std::map; #ifndef _WIN32 // TODO enable build hook on Windows struct HookInstance; #endif typedef enum {rpAccept, rpDecline, rpPostpone} HookReply; /** * Unless we are repairing, we don't both to test validity and just assume it, * so the choices are `Absent` or `Valid`. */ enum struct PathStatus { Corrupt, Absent, Valid, }; struct InitialOutputStatus { StorePath path; PathStatus status; /** * Valid in the store, and additionally non-corrupt if we are repairing */ bool isValid() const { return status == PathStatus::Valid; } /** * Merely present, allowed to be corrupt */ bool isPresent() const { return status == PathStatus::Corrupt || status == PathStatus::Valid; } }; struct InitialOutput { bool wanted; Hash outputHash; std::optional<InitialOutputStatus> known; }; /** * A goal for building some or all of the outputs of a derivation. */ struct DerivationGoal : public Goal { /** * Whether to use an on-disk .drv file. */ bool useDerivation; /** The path of the derivation. */ StorePath drvPath; /** * The goal for the corresponding resolved derivation */ std::shared_ptr<DerivationGoal> resolvedDrvGoal; /** * The specific outputs that we need to build. */ OutputsSpec wantedOutputs; /** * Mapping from input derivations + output names to actual store * paths. This is filled in by waiteeDone() as each dependency * finishes, before inputsRealised() is reached. */ std::map<std::pair<StorePath, std::string>, StorePath> inputDrvOutputs; /** * See `needRestart`; just for that field. */ enum struct NeedRestartForMoreOutputs { /** * The goal state machine is progressing based on the current value of * `wantedOutputs. No actions are needed. */ OutputsUnmodifedDontNeed, /** * `wantedOutputs` has been extended, but the state machine is * proceeding according to its old value, so we need to restart. */ OutputsAddedDoNeed, /** * The goal state machine has progressed to the point of doing a build, * in which case all outputs will be produced, so extensions to * `wantedOutputs` no longer require a restart. */ BuildInProgressWillNotNeed, }; /** * Whether additional wanted outputs have been added. */ NeedRestartForMoreOutputs needRestart = NeedRestartForMoreOutputs::OutputsUnmodifedDontNeed; /** * See `retrySubstitution`; just for that field. */ enum RetrySubstitution { /** * No issues have yet arose, no need to restart. */ NoNeed, /** * Something failed and there is an incomplete closure. Let's retry * substituting. */ YesNeed, /** * We are current or have already retried substitution, and whether or * not something goes wrong we will not retry again. */ AlreadyRetried, }; /** * Whether to retry substituting the outputs after building the * inputs. This is done in case of an incomplete closure. */ RetrySubstitution retrySubstitution = RetrySubstitution::NoNeed; /** * The derivation stored at drvPath. */ std::unique_ptr<Derivation> drv; std::unique_ptr<ParsedDerivation> parsedDrv; /** * The remainder is state held during the build. */ /** * Locks on (fixed) output paths. */ PathLocks outputLocks; /** * All input paths (that is, the union of FS closures of the * immediate input paths). */ StorePathSet inputPaths; std::map<std::string, InitialOutput> initialOutputs; /** * File descriptor for the log file. */ AutoCloseFD fdLogFile; std::shared_ptr<BufferedSink> logFileSink, logSink; /** * Number of bytes received from the builder's stdout/stderr. */ unsigned long logSize; /** * The most recent log lines. */ std::list<std::string> logTail; std::string currentLogLine; size_t currentLogLinePos = 0; // to handle carriage return std::string currentHookLine; #ifndef _WIN32 // TODO enable build hook on Windows /** * The build hook. */ std::unique_ptr<HookInstance> hook; #endif /** * The sort of derivation we are building. */ std::optional<DerivationType> derivationType; BuildMode buildMode; std::unique_ptr<MaintainCount<uint64_t>> mcExpectedBuilds, mcRunningBuilds; std::unique_ptr<Activity> act; /** * Activity that denotes waiting for a lock. */ std::unique_ptr<Activity> actLock; std::map<ActivityId, Activity> builderActivities; /** * The remote machine on which we're building. */ std::string machineName; DerivationGoal(const StorePath & drvPath, const OutputsSpec & wantedOutputs, Worker & worker, BuildMode buildMode = bmNormal); DerivationGoal(const StorePath & drvPath, const BasicDerivation & drv, const OutputsSpec & wantedOutputs, Worker & worker, BuildMode buildMode = bmNormal); virtual ~DerivationGoal(); void timedOut(Error && ex) override; std::string key() override; /** * Add wanted outputs to an already existing derivation goal. */ void addWantedOutputs(const OutputsSpec & outputs); /** * The states. */ Co init() override; Co getDerivation(); Co loadDerivation(); Co haveDerivation(); Co outputsSubstitutionTried(); Co gaveUpOnSubstitution(); Co closureRepaired(); Co inputsRealised(); Co tryToBuild(); virtual Co tryLocalBuild(); Co buildDone(); Co resolvedFinished(); /** * Is the build hook willing to perform the build? */ HookReply tryBuildHook(); virtual int getChildStatus(); /** * Check that the derivation outputs all exist and register them * as valid. */ virtual SingleDrvOutputs registerOutputs(); /** * Open a log file and a pipe to it. */ Path openLogFile(); /** * Sign the newly built realisation if the store allows it */ virtual void signRealisation(Realisation&) {} /** * Close the log file. */ void closeLogFile(); /** * Close the read side of the logger pipe. */ virtual void closeReadPipes(); /** * Cleanup hooks for buildDone() */ virtual void cleanupHookFinally(); virtual void cleanupPreChildKill(); virtual void cleanupPostChildKill(); virtual bool cleanupDecideWhetherDiskFull(); virtual void cleanupPostOutputsRegisteredModeCheck(); virtual void cleanupPostOutputsRegisteredModeNonCheck(); virtual bool isReadDesc(Descriptor fd); /** * Callback used by the worker to write to the log. */ void handleChildOutput(Descriptor fd, std::string_view data) override; void handleEOF(Descriptor fd) override; void flushLine(); /** * Wrappers around the corresponding Store methods that first consult the * derivation. This is currently needed because when there is no drv file * there also is no DB entry. */ std::map<std::string, std::optional<StorePath>> queryPartialDerivationOutputMap(); OutputPathMap queryDerivationOutputMap(); /** * Update 'initialOutputs' to determine the current status of the * outputs of the derivation. Also returns a Boolean denoting * whether all outputs are valid and non-corrupt, and a * 'SingleDrvOutputs' structure containing the valid outputs. */ std::pair<bool, SingleDrvOutputs> checkPathValidity(); /** * Aborts if any output is not valid or corrupt, and otherwise * returns a 'SingleDrvOutputs' structure containing all outputs. */ SingleDrvOutputs assertPathValidity(); /** * Forcibly kill the child process, if any. */ virtual void killChild(); Co repairClosure(); void started(); Done done( BuildResult::Status status, SingleDrvOutputs builtOutputs = {}, std::optional<Error> ex = {}); void waiteeDone(GoalPtr waitee, ExitCode result) override; StorePathSet exportReferences(const StorePathSet & storePaths); JobCategory jobCategory() const override { return JobCategory::Build; }; }; MakeError(NotDeterministic, BuildError); }
8,796
C++
.h
284
25.295775
96
0.666193
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,156
worker.hh
NixOS_nix/src/libstore/build/worker.hh
#pragma once ///@file #include "types.hh" #include "store-api.hh" #include "goal.hh" #include "realisation.hh" #include "muxable-pipe.hh" #include <future> #include <thread> namespace nix { /* Forward definition. */ struct DerivationGoal; struct PathSubstitutionGoal; class DrvOutputSubstitutionGoal; /** * Workaround for not being able to declare a something like * * ```c++ * class PathSubstitutionGoal : public Goal; * ``` * even when Goal is a complete type. * * This is still a static cast. The purpose of exporting it is to define it in * a place where `PathSubstitutionGoal` is concrete, and use it in a place where it * is opaque. */ GoalPtr upcast_goal(std::shared_ptr<PathSubstitutionGoal> subGoal); GoalPtr upcast_goal(std::shared_ptr<DrvOutputSubstitutionGoal> subGoal); typedef std::chrono::time_point<std::chrono::steady_clock> steady_time_point; /** * A mapping used to remember for each child process to what goal it * belongs, and comm channels for receiving log data and output * path creation commands. */ struct Child { WeakGoalPtr goal; Goal * goal2; // ugly hackery std::set<MuxablePipePollState::CommChannel> channels; bool respectTimeouts; bool inBuildSlot; /** * Time we last got output on stdout/stderr */ steady_time_point lastOutput; steady_time_point timeStarted; }; #ifndef _WIN32 // TODO Enable building on Windows /* Forward definition. */ struct HookInstance; #endif /** * Coordinates one or more realisations and their interdependencies. */ class Worker { private: /* Note: the worker should only have strong pointers to the top-level goals. */ /** * The top-level goals of the worker. */ Goals topGoals; /** * Goals that are ready to do some work. */ WeakGoals awake; /** * Goals waiting for a build slot. */ WeakGoals wantingToBuild; /** * Child processes currently running. */ std::list<Child> children; /** * Number of build slots occupied. This includes local builds but does not * include substitutions or remote builds via the build hook. */ size_t nrLocalBuilds; /** * Number of substitution slots occupied. */ size_t nrSubstitutions; /** * Maps used to prevent multiple instantiations of a goal for the * same derivation / path. */ std::map<StorePath, std::weak_ptr<DerivationGoal>> derivationGoals; std::map<StorePath, std::weak_ptr<PathSubstitutionGoal>> substitutionGoals; std::map<DrvOutput, std::weak_ptr<DrvOutputSubstitutionGoal>> drvOutputSubstitutionGoals; /** * Goals waiting for busy paths to be unlocked. */ WeakGoals waitingForAnyGoal; /** * Goals sleeping for a few seconds (polling a lock). */ WeakGoals waitingForAWhile; /** * Last time the goals in `waitingForAWhile` were woken up. */ steady_time_point lastWokenUp; /** * Cache for pathContentsGood(). */ std::map<StorePath, bool> pathContentsGoodCache; public: const Activity act; const Activity actDerivations; const Activity actSubstitutions; /** * Set if at least one derivation had a BuildError (i.e. permanent * failure). */ bool permanentFailure; /** * Set if at least one derivation had a timeout. */ bool timedOut; /** * Set if at least one derivation fails with a hash mismatch. */ bool hashMismatch; /** * Set if at least one derivation is not deterministic in check mode. */ bool checkMismatch; #ifdef _WIN32 AutoCloseFD ioport; #endif Store & store; Store & evalStore; #ifndef _WIN32 // TODO Enable building on Windows std::unique_ptr<HookInstance> hook; #endif uint64_t expectedBuilds = 0; uint64_t doneBuilds = 0; uint64_t failedBuilds = 0; uint64_t runningBuilds = 0; uint64_t expectedSubstitutions = 0; uint64_t doneSubstitutions = 0; uint64_t failedSubstitutions = 0; uint64_t runningSubstitutions = 0; uint64_t expectedDownloadSize = 0; uint64_t doneDownloadSize = 0; uint64_t expectedNarSize = 0; uint64_t doneNarSize = 0; /** * Whether to ask the build hook if it can build a derivation. If * it answers with "decline-permanently", we don't try again. */ bool tryBuildHook = true; Worker(Store & store, Store & evalStore); ~Worker(); /** * Make a goal (with caching). */ /** * @ref DerivationGoal "derivation goal" */ private: std::shared_ptr<DerivationGoal> makeDerivationGoalCommon( const StorePath & drvPath, const OutputsSpec & wantedOutputs, std::function<std::shared_ptr<DerivationGoal>()> mkDrvGoal); public: std::shared_ptr<DerivationGoal> makeDerivationGoal( const StorePath & drvPath, const OutputsSpec & wantedOutputs, BuildMode buildMode = bmNormal); std::shared_ptr<DerivationGoal> makeBasicDerivationGoal( const StorePath & drvPath, const BasicDerivation & drv, const OutputsSpec & wantedOutputs, BuildMode buildMode = bmNormal); /** * @ref PathSubstitutionGoal "substitution goal" */ std::shared_ptr<PathSubstitutionGoal> makePathSubstitutionGoal(const StorePath & storePath, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt); std::shared_ptr<DrvOutputSubstitutionGoal> makeDrvOutputSubstitutionGoal(const DrvOutput & id, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt); /** * Make a goal corresponding to the `DerivedPath`. * * It will be a `DerivationGoal` for a `DerivedPath::Built` or * a `SubstitutionGoal` for a `DerivedPath::Opaque`. */ GoalPtr makeGoal(const DerivedPath & req, BuildMode buildMode = bmNormal); /** * Remove a dead goal. */ void removeGoal(GoalPtr goal); /** * Wake up a goal (i.e., there is something for it to do). */ void wakeUp(GoalPtr goal); /** * Return the number of local build processes currently running (but not * remote builds via the build hook). */ size_t getNrLocalBuilds(); /** * Return the number of substitution processes currently running. */ size_t getNrSubstitutions(); /** * Registers a running child process. `inBuildSlot` means that * the process counts towards the jobs limit. */ void childStarted(GoalPtr goal, const std::set<MuxablePipePollState::CommChannel> & channels, bool inBuildSlot, bool respectTimeouts); /** * Unregisters a running child process. `wakeSleepers` should be * false if there is no sense in waking up goals that are sleeping * because they can't run yet (e.g., there is no free build slot, * or the hook would still say `postpone`). */ void childTerminated(Goal * goal, bool wakeSleepers = true); /** * Put `goal` to sleep until a build slot becomes available (which * might be right away). */ void waitForBuildSlot(GoalPtr goal); /** * Wait for any goal to finish. Pretty indiscriminate way to * wait for some resource that some other goal is holding. */ void waitForAnyGoal(GoalPtr goal); /** * Wait for a few seconds and then retry this goal. Used when * waiting for a lock held by another process. This kind of * polling is inefficient, but POSIX doesn't really provide a way * to wait for multiple locks in the main select() loop. */ void waitForAWhile(GoalPtr goal); /** * Loop until the specified top-level goals have finished. */ void run(const Goals & topGoals); /** * Wait for input to become available. */ void waitForInput(); /*** * The exit status in case of failure. * * In the case of a build failure, returned value follows this * bitmask: * * ``` * 0b1100100 * ^^^^ * |||`- timeout * ||`-- output hash mismatch * |`--- build failure * `---- not deterministic * ``` * * In other words, the failure code is at least 100 (0b1100100), but * might also be greater. * * Otherwise (no build failure, but some other sort of failure by * assumption), this returned value is 1. */ unsigned int failingExitStatus(); /** * Check whether the given valid path exists and has the right * contents. */ bool pathContentsGood(const StorePath & path); void markContentsGood(const StorePath & path); void updateProgress() { actDerivations.progress(doneBuilds, expectedBuilds + doneBuilds, runningBuilds, failedBuilds); actSubstitutions.progress(doneSubstitutions, expectedSubstitutions + doneSubstitutions, runningSubstitutions, failedSubstitutions); act.setExpected(actFileTransfer, expectedDownloadSize + doneDownloadSize); act.setExpected(actCopyPath, expectedNarSize + doneNarSize); } }; }
9,104
C++
.h
276
27.992754
178
0.682357
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,157
goal.hh
NixOS_nix/src/libstore/build/goal.hh
#pragma once ///@file #include "store-api.hh" #include "build-result.hh" #include <coroutine> namespace nix { /** * Forward definition. */ struct Goal; class Worker; /** * A pointer to a goal. */ typedef std::shared_ptr<Goal> GoalPtr; typedef std::weak_ptr<Goal> WeakGoalPtr; struct CompareGoalPtrs { bool operator() (const GoalPtr & a, const GoalPtr & b) const; }; /** * Set of goals. */ typedef std::set<GoalPtr, CompareGoalPtrs> Goals; typedef std::set<WeakGoalPtr, std::owner_less<WeakGoalPtr>> WeakGoals; /** * A map of paths to goals (and the other way around). */ typedef std::map<StorePath, WeakGoalPtr> WeakGoalMap; /** * Used as a hint to the worker on how to schedule a particular goal. For example, * builds are typically CPU- and memory-bound, while substitutions are I/O bound. * Using this information, the worker might decide to schedule more or fewer goals * of each category in parallel. */ enum struct JobCategory { /** * A build of a derivation; it will use CPU and disk resources. */ Build, /** * A substitution an arbitrary store object; it will use network resources. */ Substitution, }; struct Goal : public std::enable_shared_from_this<Goal> { typedef enum {ecBusy, ecSuccess, ecFailed, ecNoSubstituters, ecIncompleteClosure} ExitCode; /** * Backlink to the worker. */ Worker & worker; /** * Goals that this goal is waiting for. */ Goals waitees; /** * Goals waiting for this one to finish. Must use weak pointers * here to prevent cycles. */ WeakGoals waiters; /** * Number of goals we are/were waiting for that have failed. */ size_t nrFailed = 0; /** * Number of substitution goals we are/were waiting for that * failed because there are no substituters. */ size_t nrNoSubstituters = 0; /** * Number of substitution goals we are/were waiting for that * failed because they had unsubstitutable references. */ size_t nrIncompleteClosure = 0; /** * Name of this goal for debugging purposes. */ std::string name; /** * Whether the goal is finished. */ ExitCode exitCode = ecBusy; protected: /** * Build result. */ BuildResult buildResult; public: /** * Suspend our goal and wait until we get `work`-ed again. * `co_await`-able by @ref Co. */ struct Suspend {}; /** * Return from the current coroutine and suspend our goal * if we're not busy anymore, or jump to the next coroutine * set to be executed/resumed. */ struct Return {}; /** * `co_return`-ing this will end the goal. * If you're not inside a coroutine, you can safely discard this. */ struct [[nodiscard]] Done { private: Done(){} friend Goal; }; // forward declaration of promise_type, see below struct promise_type; /** * Handle to coroutine using @ref Co and @ref promise_type. */ using handle_type = std::coroutine_handle<promise_type>; /** * C++20 coroutine wrapper for use in goal logic. * Coroutines are functions that use `co_await`/`co_return` (and `co_yield`, but not supported by @ref Co). * * @ref Co is meant to be used by methods of subclasses of @ref Goal. * The main functionality provided by `Co` is * - `co_await Suspend{}`: Suspends the goal. * - `co_await f()`: Waits until `f()` finishes. * - `co_return f()`: Tail-calls `f()`. * - `co_return Return{}`: Ends coroutine. * * The idea is that you implement the goal logic using coroutines, * and do the core thing a goal can do, suspension, when you have * children you're waiting for. * Coroutines allow you to resume the work cleanly. * * @note Brief explanation of C++20 coroutines: * When you `Co f()`, a `std::coroutine_handle<promise_type>` is created, * alongside its @ref promise_type. * There are suspension points at the beginning of the coroutine, * at every `co_await`, and at the final (possibly implicit) `co_return`. * Once suspended, you can resume the `std::coroutine_handle` by doing `coroutine_handle.resume()`. * Suspension points are implemented by passing a struct to the compiler * that implements `await_sus`pend. * `await_suspend` can either say "cancel suspension", in which case execution resumes, * "suspend", in which case control is passed back to the caller of `coroutine_handle.resume()` * or the place where the coroutine function is initially executed in the case of the initial * suspension, or `await_suspend` can specify another coroutine to jump to, which is * how tail calls are implemented. * * @note Resources: * - https://lewissbaker.github.io/ * - https://www.chiark.greenend.org.uk/~sgtatham/quasiblog/coroutines-c++20/ * - https://www.scs.stanford.edu/~dm/blog/c++-coroutines.html * * @todo Allocate explicitly on stack since HALO thing doesn't really work, * specifically, there's no way to uphold the requirements when trying to do * tail-calls without using a trampoline AFAICT. * * @todo Support returning data natively */ struct [[nodiscard]] Co { /** * The underlying handle. */ handle_type handle; explicit Co(handle_type handle) : handle(handle) {}; void operator=(Co&&); Co(Co&& rhs); ~Co(); bool await_ready() { return false; }; /** * When we `co_await` another `Co`-returning coroutine, * we tell the caller of `caller_coroutine.resume()` to switch to our coroutine (@ref handle). * To make sure we return to the original coroutine, we set it as the continuation of our * coroutine. In @ref promise_type::final_awaiter we check if it's set and if so we return to it. * * To explain in more understandable terms: * When we `co_await Co_returning_function()`, this function is called on the resultant @ref Co of * the _called_ function, and C++ automatically passes the caller in. * * `goal` field of @ref promise_type is also set here by copying it from the caller. */ std::coroutine_handle<> await_suspend(handle_type handle); void await_resume() {}; }; /** * Used on initial suspend, does the same as `std::suspend_always`, * but asserts that everything has been set correctly. */ struct InitialSuspend { /** * Handle of coroutine that does the * initial suspend */ handle_type handle; bool await_ready() { return false; }; void await_suspend(handle_type handle_) { handle = handle_; } void await_resume() { assert(handle); assert(handle.promise().goal); // goal must be set assert(handle.promise().goal->top_co); // top_co of goal must be set assert(handle.promise().goal->top_co->handle == handle); // top_co of goal must be us } }; /** * Promise type for coroutines defined using @ref Co. * Attached to coroutine handle. */ struct promise_type { /** * Either this is who called us, or it is who we will tail-call. * It is what we "jump" to once we are done. */ std::optional<Co> continuation; /** * The goal that we're a part of. * Set either in @ref Co::await_suspend or in constructor of @ref Goal. */ Goal* goal = nullptr; /** * Is set to false when destructed to ensure we don't use a * destructed coroutine by accident */ bool alive = true; /** * The awaiter used by @ref final_suspend. */ struct final_awaiter { bool await_ready() noexcept { return false; }; /** * Here we execute our continuation, by passing it back to the caller. * C++ compiler will create code that takes that and executes it promptly. * `h` is the handle for the coroutine that is finishing execution, * thus it must be destroyed. */ std::coroutine_handle<> await_suspend(handle_type h) noexcept; void await_resume() noexcept { assert(false); }; }; /** * Called by compiler generated code to construct the `Co` * that is returned from a `Co`-returning coroutine. */ Co get_return_object(); /** * Called by compiler generated code before body of coroutine. * We use this opportunity to set the @ref goal field * and `top_co` field of @ref Goal. */ InitialSuspend initial_suspend() { return {}; }; /** * Called on `co_return`. Creates @ref final_awaiter which * either jumps to continuation or suspends goal. */ final_awaiter final_suspend() noexcept { return {}; }; /** * Does nothing, but provides an opportunity for * @ref final_suspend to happen. */ void return_value(Return) {} /** * Does nothing, but provides an opportunity for * @ref final_suspend to happen. */ void return_value(Done) {} /** * When "returning" another coroutine, what happens is that * we set it as our own continuation, thus once the final suspend * happens, we transfer control to it. * The original continuation we had is set as the continuation * of the coroutine passed in. * @ref final_suspend is called after this, and @ref final_awaiter will * pass control off to @ref continuation. * * If we already have a continuation, that continuation is set as * the continuation of the new continuation. Thus, the continuation * passed to @ref return_value must not have a continuation set. */ void return_value(Co&&); /** * If an exception is thrown inside a coroutine, * we re-throw it in the context of the "resumer" of the continuation. */ void unhandled_exception() { throw; }; /** * Allows awaiting a @ref Co. */ Co&& await_transform(Co&& co) { return static_cast<Co&&>(co); } /** * Allows awaiting a @ref Suspend. * Always suspends. */ std::suspend_always await_transform(Suspend) { return {}; }; }; /** * The coroutine being currently executed. * MUST be updated when switching the coroutine being executed. * This is used both for memory management and to resume the last * coroutine executed. * Destroying this should destroy all coroutines created for this goal. */ std::optional<Co> top_co; /** * The entry point for the goal */ virtual Co init() = 0; /** * Wrapper around @ref init since virtual functions * can't be used in constructors. */ inline Co init_wrapper(); /** * Signals that the goal is done. * `co_return` the result. If you're not inside a coroutine, you can ignore * the return value safely. */ Done amDone(ExitCode result, std::optional<Error> ex = {}); virtual void cleanup() { } /** * Project a `BuildResult` with just the information that pertains * to the given request. * * In general, goals may be aliased between multiple requests, and * the stored `BuildResult` has information for the union of all * requests. We don't want to leak what the other request are for * sake of both privacy and determinism, and this "safe accessor" * ensures we don't. */ BuildResult getBuildResult(const DerivedPath &) const; /** * Exception containing an error message, if any. */ std::optional<Error> ex; Goal(Worker & worker, DerivedPath path) : worker(worker), top_co(init_wrapper()) { // top_co shouldn't have a goal already, should be nullptr. assert(!top_co->handle.promise().goal); // we set it such that top_co can pass it down to its subcoroutines. top_co->handle.promise().goal = this; } virtual ~Goal() { trace("goal destroyed"); } void work(); void addWaitee(GoalPtr waitee); virtual void waiteeDone(GoalPtr waitee, ExitCode result); virtual void handleChildOutput(Descriptor fd, std::string_view data) { unreachable(); } virtual void handleEOF(Descriptor fd) { unreachable(); } void trace(std::string_view s); std::string getName() const { return name; } /** * Callback in case of a timeout. It should wake up its waiters, * get rid of any running child processes that are being monitored * by the worker (important!), etc. */ virtual void timedOut(Error && ex) = 0; virtual std::string key() = 0; /** * @brief Hint for the scheduler, which concurrency limit applies. * @see JobCategory */ virtual JobCategory jobCategory() const = 0; }; void addToWeakGoals(WeakGoals & goals, GoalPtr p); } template<typename... ArgTypes> struct std::coroutine_traits<nix::Goal::Co, ArgTypes...> { using promise_type = nix::Goal::promise_type; }; nix::Goal::Co nix::Goal::init_wrapper() { co_return init(); }
13,771
C++
.h
379
29.585752
111
0.621267
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,158
nix_api_store_internal.h
NixOS_nix/src/libstore-c/nix_api_store_internal.h
#ifndef NIX_API_STORE_INTERNAL_H #define NIX_API_STORE_INTERNAL_H #include "store-api.hh" struct Store { nix::ref<nix::Store> ptr; }; struct StorePath { nix::StorePath path; }; #endif
195
C++
.h
12
14.333333
32
0.738889
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,159
nix_api_store.h
NixOS_nix/src/libstore-c/nix_api_store.h
#ifndef NIX_API_STORE_H #define NIX_API_STORE_H /** * @defgroup libstore libstore * @brief C bindings for nix libstore * * libstore is used for talking to a Nix store * @{ */ /** @file * @brief Main entry for the libstore C bindings */ #include "nix_api_util.h" #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif // cffi start /** @brief Reference to a Nix store */ typedef struct Store Store; /** @brief Nix store path */ typedef struct StorePath StorePath; /** * @brief Initializes the Nix store library * * This function should be called before creating a Store * This function can be called multiple times. * * @param[out] context Optional, stores error information * @return NIX_OK if the initialization was successful, an error code otherwise. */ nix_err nix_libstore_init(nix_c_context * context); /** * @brief Like nix_libstore_init, but does not load the Nix configuration. * * This is useful when external configuration is not desired, such as when running unit tests. */ nix_err nix_libstore_init_no_load_config(nix_c_context * context); /** * @brief Open a nix store. * * Store instances may share state and resources behind the scenes. * * @param[out] context Optional, stores error information * @param[in] uri URI of the Nix store, copied. See [*Store URL format* in the Nix Reference * Manual](https://nixos.org/manual/nix/stable/store/types/#store-url-format). * @param[in] params optional, null-terminated array of key-value pairs, e.g. {{"endpoint", * "https://s3.local"}}. See [*Store Types* in the Nix Reference * Manual](https://nixos.org/manual/nix/stable/store/types). * @return a Store pointer, NULL in case of errors * @see nix_store_free */ Store * nix_store_open(nix_c_context * context, const char * uri, const char *** params); /** * @brief Deallocate a nix store and free any resources if not also held by other Store instances. * * Does not fail. * * @param[in] store the store to free */ void nix_store_free(Store * store); /** * @brief get the URI of a nix store * @param[out] context Optional, stores error information * @param[in] store nix store reference * @param[in] callback Called with the URI. * @param[in] user_data optional, arbitrary data, passed to the callback when it's called. * @see nix_get_string_callback * @return error code, NIX_OK on success. */ nix_err nix_store_get_uri(nix_c_context * context, Store * store, nix_get_string_callback callback, void * user_data); // returns: owned StorePath* /** * @brief Parse a Nix store path into a StorePath * * @note Don't forget to free this path using nix_store_path_free()! * @param[out] context Optional, stores error information * @param[in] store nix store reference * @param[in] path Path string to parse, copied * @return owned store path, NULL on error */ StorePath * nix_store_parse_path(nix_c_context * context, Store * store, const char * path); /** * @brief Get the path name (e.g. "name" in /nix/store/...-name) * * @param[in] store_path the path to get the name from * @param[in] callback called with the name * @param[in] user_data arbitrary data, passed to the callback when it's called. */ void nix_store_path_name(const StorePath * store_path, nix_get_string_callback callback, void * user_data); /** * @brief Copy a StorePath * * @param[in] p the path to copy * @return a new StorePath */ StorePath * nix_store_path_clone(const StorePath * p); /** @brief Deallocate a StorePath * * Does not fail. * @param[in] p the path to free */ void nix_store_path_free(StorePath * p); /** * @brief Check if a StorePath is valid (i.e. that corresponding store object and its closure of references exists in * the store) * @param[out] context Optional, stores error information * @param[in] store Nix Store reference * @param[in] path Path to check * @return true or false, error info in context */ bool nix_store_is_valid_path(nix_c_context * context, Store * store, StorePath * path); // nix_err nix_store_ensure(Store*, const char*); // nix_err nix_store_build_paths(Store*); /** * @brief Realise a Nix store path * * Blocking, calls callback once for each realised output. * * @note When working with expressions, consider using e.g. nix_string_realise to get the output. `.drvPath` may not be * accurate or available in the future. See https://github.com/NixOS/nix/issues/6507 * * @param[out] context Optional, stores error information * @param[in] store Nix Store reference * @param[in] path Path to build * @param[in] userdata data to pass to every callback invocation * @param[in] callback called for every realised output */ nix_err nix_store_realise( nix_c_context * context, Store * store, StorePath * path, void * userdata, void (*callback)(void * userdata, const char * outname, const char * out)); /** * @brief get the version of a nix store. * * If the store doesn't have a version (like the dummy store), returns an empty string. * * @param[out] context Optional, stores error information * @param[in] store nix store reference * @param[in] callback Called with the version. * @param[in] user_data optional, arbitrary data, passed to the callback when it's called. * @see nix_get_string_callback * @return error code, NIX_OK on success. */ nix_err nix_store_get_version(nix_c_context * context, Store * store, nix_get_string_callback callback, void * user_data); /** * @brief Copy the closure of `path` from `srcStore` to `dstStore`. * * @param[out] context Optional, stores error information * @param[in] srcStore nix source store reference * @param[in] dstStore nix destination store reference * @param[in] path Path to copy */ nix_err nix_store_copy_closure(nix_c_context * context, Store * srcStore, Store * dstStore, StorePath * path); // cffi end #ifdef __cplusplus } #endif /** * @} */ #endif // NIX_API_STORE_H
5,891
C++
.h
165
33.818182
119
0.725744
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,160
libexpr.hh
NixOS_nix/src/libexpr-test-support/tests/libexpr.hh
#pragma once ///@file #include <gtest/gtest.h> #include <gmock/gmock.h> #include "fetch-settings.hh" #include "value.hh" #include "nixexpr.hh" #include "nixexpr.hh" #include "eval.hh" #include "eval-gc.hh" #include "eval-inline.hh" #include "eval-settings.hh" #include "tests/libstore.hh" namespace nix { class LibExprTest : public LibStoreTest { public: static void SetUpTestSuite() { LibStoreTest::SetUpTestSuite(); initGC(); } protected: LibExprTest() : LibStoreTest() , state({}, store, fetchSettings, evalSettings, nullptr) { evalSettings.nixPath = {}; } Value eval(std::string input, bool forceValue = true) { Value v; Expr * e = state.parseExprFromString(input, state.rootPath(CanonPath::root)); assert(e); state.eval(e, v); if (forceValue) state.forceValue(v, noPos); return v; } Symbol createSymbol(const char * value) { return state.symbols.create(value); } bool readOnlyMode = true; fetchers::Settings fetchSettings{}; EvalSettings evalSettings{readOnlyMode}; EvalState state; }; MATCHER(IsListType, "") { return arg != nList; } MATCHER(IsList, "") { return arg.type() == nList; } MATCHER(IsString, "") { return arg.type() == nString; } MATCHER(IsNull, "") { return arg.type() == nNull; } MATCHER(IsThunk, "") { return arg.type() == nThunk; } MATCHER(IsAttrs, "") { return arg.type() == nAttrs; } MATCHER_P(IsStringEq, s, fmt("The string is equal to \"%1%\"", s)) { if (arg.type() != nString) { return false; } return std::string_view(arg.c_str()) == s; } MATCHER_P(IsIntEq, v, fmt("The string is equal to \"%1%\"", v)) { if (arg.type() != nInt) { return false; } return arg.integer().value == v; } MATCHER_P(IsFloatEq, v, fmt("The float is equal to \"%1%\"", v)) { if (arg.type() != nFloat) { return false; } return arg.fpoint() == v; } MATCHER(IsTrue, "") { if (arg.type() != nBool) { return false; } return arg.boolean() == true; } MATCHER(IsFalse, "") { if (arg.type() != nBool) { return false; } return arg.boolean() == false; } MATCHER_P(IsPathEq, p, fmt("Is a path equal to \"%1%\"", p)) { if (arg.type() != nPath) { *result_listener << "Expected a path got " << arg.type(); return false; } else { auto path = arg.path(); if (path.path != CanonPath(p)) { *result_listener << "Expected a path that equals \"" << p << "\" but got: " << path.path; return false; } } return true; } MATCHER_P(IsListOfSize, n, fmt("Is a list of size [%1%]", n)) { if (arg.type() != nList) { *result_listener << "Expected list got " << arg.type(); return false; } else if (arg.listSize() != (size_t)n) { *result_listener << "Expected as list of size " << n << " got " << arg.listSize(); return false; } return true; } MATCHER_P(IsAttrsOfSize, n, fmt("Is a set of size [%1%]", n)) { if (arg.type() != nAttrs) { *result_listener << "Expected set got " << arg.type(); return false; } else if (arg.attrs()->size() != (size_t) n) { *result_listener << "Expected a set with " << n << " attributes but got " << arg.attrs()->size(); return false; } return true; } } /* namespace nix */
4,013
C++
.h
126
22.595238
109
0.499094
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,161
nix_api_expr.hh
NixOS_nix/src/libexpr-test-support/tests/nix_api_expr.hh
#pragma once ///@file #include "nix_api_expr.h" #include "nix_api_value.h" #include "tests/nix_api_store.hh" #include <gtest/gtest.h> namespace nixC { class nix_api_expr_test : public nix_api_store_test { protected: nix_api_expr_test() { nix_libexpr_init(ctx); state = nix_state_create(nullptr, nullptr, store); value = nix_alloc_value(nullptr, state); } ~nix_api_expr_test() { nix_gc_decref(nullptr, value); nix_state_free(state); } EvalState * state; nix_value * value; }; }
555
C++
.h
25
18.08
58
0.641221
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,162
context.hh
NixOS_nix/src/libexpr-test-support/tests/value/context.hh
#pragma once ///@file #include <rapidcheck/gen/Arbitrary.h> #include "value/context.hh" namespace rc { using namespace nix; template<> struct Arbitrary<NixStringContextElem::Opaque> { static Gen<NixStringContextElem::Opaque> arbitrary(); }; template<> struct Arbitrary<NixStringContextElem::Built> { static Gen<NixStringContextElem::Built> arbitrary(); }; template<> struct Arbitrary<NixStringContextElem::DrvDeep> { static Gen<NixStringContextElem::DrvDeep> arbitrary(); }; template<> struct Arbitrary<NixStringContextElem> { static Gen<NixStringContextElem> arbitrary(); }; }
602
C++
.h
23
24.130435
58
0.793345
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,163
variant-wrapper.hh
NixOS_nix/src/libutil/variant-wrapper.hh
#pragma once ///@file // not used, but will be used by callers #include <variant> /** * Force the default versions of all constructors (copy, move, copy * assignment). */ #define FORCE_DEFAULT_CONSTRUCTORS(CLASS_NAME) \ CLASS_NAME(const CLASS_NAME &) = default; \ CLASS_NAME(CLASS_NAME &) = default; \ CLASS_NAME(CLASS_NAME &&) = default; \ \ CLASS_NAME & operator =(const CLASS_NAME &) = default; \ CLASS_NAME & operator =(CLASS_NAME &) = default; /** * Make a wrapper constructor. All args are forwarded to the * construction of the "raw" field. (Which we assume is the only one.) * * The moral equivalent of `using Raw::Raw;` */ #define MAKE_WRAPPER_CONSTRUCTOR(CLASS_NAME) \ FORCE_DEFAULT_CONSTRUCTORS(CLASS_NAME) \ \ CLASS_NAME(auto &&... arg) \ : raw(std::forward<decltype(arg)>(arg)...) \ { }
859
C++
.h
27
28.62963
70
0.66345
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,164
tarfile.hh
NixOS_nix/src/libutil/tarfile.hh
#pragma once ///@file #include "serialise.hh" #include "fs-sink.hh" #include <archive.h> namespace nix { struct TarArchive { struct archive * archive; Source * source; std::vector<unsigned char> buffer; void check(int err, const std::string & reason = "failed to extract archive (%s)"); explicit TarArchive(const std::filesystem::path & path); /// @brief Create a generic archive from source. /// @param source - Input byte stream. /// @param raw - Whether to enable raw file support. For more info look in docs: /// https://manpages.debian.org/stretch/libarchive-dev/archive_read_format.3.en.html /// @param compression_method - Primary compression method to use. std::nullopt means 'all'. TarArchive(Source & source, bool raw = false, std::optional<std::string> compression_method = std::nullopt); /// Disable copy constructor. Explicitly default move assignment/constructor. TarArchive(const TarArchive &) = delete; TarArchive & operator=(const TarArchive &) = delete; TarArchive(TarArchive &&) = default; TarArchive & operator=(TarArchive &&) = default; void close(); ~TarArchive(); }; int getArchiveFilterCodeByName(const std::string & method); void unpackTarfile(Source & source, const std::filesystem::path & destDir); void unpackTarfile(const std::filesystem::path & tarFile, const std::filesystem::path & destDir); time_t unpackTarfileToSink(TarArchive & archive, ExtendedFileSystemObjectSink & parseSink); }
1,504
C++
.h
32
43.3125
112
0.728395
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,165
config.hh
NixOS_nix/src/libutil/config.hh
#pragma once ///@file #include <cassert> #include <map> #include <set> #include <nlohmann/json_fwd.hpp> #include "types.hh" #include "experimental-features.hh" namespace nix { /** * The Config class provides Nix runtime configurations. * * What is a Configuration? * A collection of uniquely named Settings. * * What is a Setting? * Each property that you can set in a configuration corresponds to a * `Setting`. A setting records value and description of a property * with a default and optional aliases. * * A valid configuration consists of settings that are registered to a * `Config` object instance: * * Config config; * Setting<std::string> systemSetting{&config, "x86_64-linux", "system", "the current system"}; * * The above creates a `Config` object and registers a setting called "system" * via the variable `systemSetting` with it. The setting defaults to the string * "x86_64-linux", it's description is "the current system". All of the * registered settings can then be accessed as shown below: * * std::map<std::string, Config::SettingInfo> settings; * config.getSettings(settings); * settings["system"].description == "the current system" * settings["system"].value == "x86_64-linux" * * * The above retrieves all currently known settings from the `Config` object * and adds them to the `settings` map. */ class Args; class AbstractSetting; class AbstractConfig { protected: StringMap unknownSettings; AbstractConfig(StringMap initials = {}); public: /** * Sets the value referenced by `name` to `value`. Returns true if the * setting is known, false otherwise. */ virtual bool set(const std::string & name, const std::string & value) = 0; struct SettingInfo { std::string value; std::string description; }; /** * Adds the currently known settings to the given result map `res`. * - res: map to store settings in * - overriddenOnly: when set to true only overridden settings will be added to `res` */ virtual void getSettings(std::map<std::string, SettingInfo> & res, bool overriddenOnly = false) = 0; /** * Parses the configuration in `contents` and applies it * - contents: configuration contents to be parsed and applied * - path: location of the configuration file */ void applyConfig(const std::string & contents, const std::string & path = "<unknown>"); /** * Resets the `overridden` flag of all Settings */ virtual void resetOverridden() = 0; /** * Outputs all settings to JSON * - out: JSONObject to write the configuration to */ virtual nlohmann::json toJSON() = 0; /** * Outputs all settings in a key-value pair format suitable to be used as * `nix.conf` */ virtual std::string toKeyValue() = 0; /** * Converts settings to `Args` to be used on the command line interface * - args: args to write to * - category: category of the settings */ virtual void convertToArgs(Args & args, const std::string & category) = 0; /** * Logs a warning for each unregistered setting */ void warnUnknownSettings(); /** * Re-applies all previously attempted changes to unknown settings */ void reapplyUnknownSettings(); }; /** * A class to simplify providing configuration settings. The typical * use is to inherit Config and add Setting<T> members: * * class MyClass : private Config * { * Setting<int> foo{this, 123, "foo", "the number of foos to use"}; * Setting<std::string> bar{this, "blabla", "bar", "the name of the bar"}; * * MyClass() : Config(readConfigFile("/etc/my-app.conf")) * { * std::cout << foo << "\n"; // will print 123 unless overridden * } * }; */ class Config : public AbstractConfig { friend class AbstractSetting; public: struct SettingData { bool isAlias; AbstractSetting * setting; }; using Settings = std::map<std::string, SettingData>; private: Settings _settings; public: Config(StringMap initials = {}); bool set(const std::string & name, const std::string & value) override; void addSetting(AbstractSetting * setting); void getSettings(std::map<std::string, SettingInfo> & res, bool overriddenOnly = false) override; void resetOverridden() override; nlohmann::json toJSON() override; std::string toKeyValue() override; void convertToArgs(Args & args, const std::string & category) override; }; class AbstractSetting { friend class Config; public: const std::string name; const std::string description; const std::set<std::string> aliases; int created = 123; bool overridden = false; std::optional<ExperimentalFeature> experimentalFeature; protected: AbstractSetting( const std::string & name, const std::string & description, const std::set<std::string> & aliases, std::optional<ExperimentalFeature> experimentalFeature = std::nullopt); virtual ~AbstractSetting(); virtual void set(const std::string & value, bool append = false) = 0; /** * Whether the type is appendable; i.e. whether the `append` * parameter to `set()` is allowed to be `true`. */ virtual bool isAppendable() = 0; virtual std::string to_string() const = 0; nlohmann::json toJSON(); virtual std::map<std::string, nlohmann::json> toJSONObject() const; virtual void convertToArg(Args & args, const std::string & category); bool isOverridden() const; }; /** * A setting of type T. */ template<typename T> class BaseSetting : public AbstractSetting { protected: T value; const T defaultValue; const bool documentDefault; /** * Parse the string into a `T`. * * Used by `set()`. */ virtual T parse(const std::string & str) const; /** * Append or overwrite `value` with `newValue`. * * Some types to do not support appending in which case `append` * should never be passed. The default handles this case. * * @param append Whether to append or overwrite. */ virtual void appendOrSet(T newValue, bool append); public: BaseSetting(const T & def, const bool documentDefault, const std::string & name, const std::string & description, const std::set<std::string> & aliases = {}, std::optional<ExperimentalFeature> experimentalFeature = std::nullopt) : AbstractSetting(name, description, aliases, experimentalFeature) , value(def) , defaultValue(def) , documentDefault(documentDefault) { } operator const T &() const { return value; } operator T &() { return value; } const T & get() const { return value; } template<typename U> bool operator ==(const U & v2) const { return value == v2; } template<typename U> bool operator !=(const U & v2) const { return value != v2; } template<typename U> void operator =(const U & v) { assign(v); } virtual void assign(const T & v) { value = v; } template<typename U> void setDefault(const U & v) { if (!overridden) value = v; } /** * Require any experimental feature the setting depends on * * Uses `parse()` to get the value from `str`, and `appendOrSet()` * to set it. */ void set(const std::string & str, bool append = false) override final; /** * C++ trick; This is template-specialized to compile-time indicate whether * the type is appendable. */ struct trait; /** * Always defined based on the C++ magic * with `trait` above. */ bool isAppendable() override final; virtual void override(const T & v) { overridden = true; value = v; } std::string to_string() const override; void convertToArg(Args & args, const std::string & category) override; std::map<std::string, nlohmann::json> toJSONObject() const override; }; template<typename T> std::ostream & operator <<(std::ostream & str, const BaseSetting<T> & opt) { return str << static_cast<const T &>(opt); } template<typename T> bool operator ==(const T & v1, const BaseSetting<T> & v2) { return v1 == static_cast<const T &>(v2); } template<typename T> class Setting : public BaseSetting<T> { public: Setting(Config * options, const T & def, const std::string & name, const std::string & description, const std::set<std::string> & aliases = {}, const bool documentDefault = true, std::optional<ExperimentalFeature> experimentalFeature = std::nullopt) : BaseSetting<T>(def, documentDefault, name, description, aliases, std::move(experimentalFeature)) { options->addSetting(this); } void operator =(const T & v) { this->assign(v); } }; /** * A special setting for Paths. These are automatically canonicalised * (e.g. "/foo//bar/" becomes "/foo/bar"). * * It is mandatory to specify a path; i.e. the empty string is not * permitted. */ class PathSetting : public BaseSetting<Path> { public: PathSetting(Config * options, const Path & def, const std::string & name, const std::string & description, const std::set<std::string> & aliases = {}); Path parse(const std::string & str) const override; Path operator +(const char * p) const { return value + p; } void operator =(const Path & v) { this->assign(v); } }; /** * Like `PathSetting`, but the absence of a path is also allowed. * * `std::optional` is used instead of the empty string for clarity. */ class OptionalPathSetting : public BaseSetting<std::optional<Path>> { public: OptionalPathSetting(Config * options, const std::optional<Path> & def, const std::string & name, const std::string & description, const std::set<std::string> & aliases = {}); std::optional<Path> parse(const std::string & str) const override; void operator =(const std::optional<Path> & v); }; struct ExperimentalFeatureSettings : Config { Setting<std::set<ExperimentalFeature>> experimentalFeatures{ this, {}, "experimental-features", R"( Experimental features that are enabled. Example: ``` experimental-features = nix-command flakes ``` The following experimental features are available: {{#include experimental-features-shortlist.md}} Experimental features are [further documented in the manual](@docroot@/development/experimental-features.md). )"}; /** * Check whether the given experimental feature is enabled. */ bool isEnabled(const ExperimentalFeature &) const; /** * Require an experimental feature be enabled, throwing an error if it is * not. */ void require(const ExperimentalFeature &) const; /** * `std::nullopt` pointer means no feature, which means there is nothing that could be * disabled, and so the function returns true in that case. */ bool isEnabled(const std::optional<ExperimentalFeature> &) const; /** * `std::nullopt` pointer means no feature, which means there is nothing that could be * disabled, and so the function does nothing in that case. */ void require(const std::optional<ExperimentalFeature> &) const; }; // FIXME: don't use a global variable. extern ExperimentalFeatureSettings experimentalFeatureSettings; }
11,579
C++
.h
335
29.749254
119
0.669865
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,166
file-path.hh
NixOS_nix/src/libutil/file-path.hh
#pragma once ///@file #include <filesystem> #include "types.hh" #include "os-string.hh" namespace nix { /** * Paths are just `std::filesystem::path`s. * * @todo drop `NG` suffix and replace the ones in `types.hh`. */ typedef std::list<std::filesystem::path> PathsNG; typedef std::set<std::filesystem::path> PathSetNG; /** * Stop gap until `std::filesystem::path_view` from P1030R6 exists in a * future C++ standard. * * @todo drop `NG` suffix and replace the one in `types.hh`. */ struct PathViewNG : OsStringView { using string_view = OsStringView; using string_view::string_view; PathViewNG(const std::filesystem::path & path) : OsStringView{path.native()} { } PathViewNG(const OsString & path) : OsStringView{path} { } const string_view & native() const { return *this; } string_view & native() { return *this; } }; std::optional<std::filesystem::path> maybePath(PathView path); std::filesystem::path pathNG(PathView path); }
998
C++
.h
35
25.542857
71
0.692955
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,167
exec.hh
NixOS_nix/src/libutil/exec.hh
#pragma once #include "os-string.hh" namespace nix { /** * `execvpe` is a GNU extension, so we need to implement it for other POSIX * platforms. * * We use our own implementation unconditionally for consistency. */ int execvpe(const OsChar * file0, const OsChar * const argv[], const OsChar * const envp[]); }
319
C++
.h
11
27.181818
92
0.736842
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,168
comparator.hh
NixOS_nix/src/libutil/comparator.hh
#pragma once ///@file #define GENERATE_ONE_CMP(PRE, RET, QUAL, COMPARATOR, MY_TYPE, ...) \ PRE RET QUAL operator COMPARATOR(const MY_TYPE & other) const noexcept { \ __VA_OPT__(const MY_TYPE * me = this;) \ auto fields1 = std::tie( __VA_ARGS__ ); \ __VA_OPT__(me = &other;) \ auto fields2 = std::tie( __VA_ARGS__ ); \ return fields1 COMPARATOR fields2; \ } #define GENERATE_EQUAL(prefix, qualification, my_type, args...) \ GENERATE_ONE_CMP(prefix, bool, qualification, ==, my_type, args) #define GENERATE_SPACESHIP(prefix, ret, qualification, my_type, args...) \ GENERATE_ONE_CMP(prefix, ret, qualification, <=>, my_type, args) /** * Awful hacky generation of the comparison operators by doing a lexicographic * comparison between the choosen fields. * * ``` * GENERATE_CMP(ClassName, me->field1, me->field2, ...) * ``` * * will generate comparison operators semantically equivalent to: * * ``` * auto operator<=>(const ClassName& other) const noexcept { * if (auto cmp = field1 <=> other.field1; cmp != 0) * return cmp; * if (auto cmp = field2 <=> other.field2; cmp != 0) * return cmp; * ... * return 0; * } * ``` */ #define GENERATE_CMP(args...) \ GENERATE_EQUAL(,,args) \ GENERATE_SPACESHIP(,auto,,args) /** * @param prefix This is for something before each declaration like * `template<classname Foo>`. * * @param my_type the type are defining operators for. */ #define GENERATE_CMP_EXT(prefix, ret, my_type, args...) \ GENERATE_EQUAL(prefix, my_type ::, my_type, args) \ GENERATE_SPACESHIP(prefix, ret, my_type ::, my_type, args)
1,643
C++
.h
47
32.042553
78
0.649718
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,169
file-descriptor.hh
NixOS_nix/src/libutil/file-descriptor.hh
#pragma once ///@file #include "types.hh" #include "error.hh" #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # include <windows.h> #endif namespace nix { struct Sink; struct Source; /** * Operating System capability */ using Descriptor = #if _WIN32 HANDLE #else int #endif ; const Descriptor INVALID_DESCRIPTOR = #if _WIN32 INVALID_HANDLE_VALUE #else -1 #endif ; /** * Convert a native `Descriptor` to a POSIX file descriptor * * This is a no-op except on Windows. */ static inline Descriptor toDescriptor(int fd) { #ifdef _WIN32 return reinterpret_cast<HANDLE>(_get_osfhandle(fd)); #else return fd; #endif } /** * Convert a POSIX file descriptor to a native `Descriptor` in read-only * mode. * * This is a no-op except on Windows. */ static inline int fromDescriptorReadOnly(Descriptor fd) { #ifdef _WIN32 return _open_osfhandle(reinterpret_cast<intptr_t>(fd), _O_RDONLY); #else return fd; #endif } /** * Read the contents of a resource into a string. */ std::string readFile(Descriptor fd); /** * Wrappers arount read()/write() that read/write exactly the * requested number of bytes. */ void readFull(Descriptor fd, char * buf, size_t count); void writeFull(Descriptor fd, std::string_view s, bool allowInterrupts = true); /** * Read a line from a file descriptor. * * @param fd The file descriptor to read from * @param eofOk If true, return an unterminated line if EOF is reached. (e.g. the empty string) * * @return A line of text ending in `\n`, or a string without `\n` if `eofOk` is true and EOF is reached. */ std::string readLine(Descriptor fd, bool eofOk = false); /** * Write a line to a file descriptor. */ void writeLine(Descriptor fd, std::string s); /** * Read a file descriptor until EOF occurs. */ std::string drainFD(Descriptor fd, bool block = true, const size_t reserveSize=0); /** * The Windows version is always blocking. */ void drainFD( Descriptor fd , Sink & sink #ifndef _WIN32 , bool block = true #endif ); /** * Get [Standard Input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)) */ [[gnu::always_inline]] inline Descriptor getStandardInput() { #ifndef _WIN32 return STDIN_FILENO; #else return GetStdHandle(STD_INPUT_HANDLE); #endif } /** * Get [Standard Output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) */ [[gnu::always_inline]] inline Descriptor getStandardOutput() { #ifndef _WIN32 return STDOUT_FILENO; #else return GetStdHandle(STD_OUTPUT_HANDLE); #endif } /** * Get [Standard Error](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) */ [[gnu::always_inline]] inline Descriptor getStandardError() { #ifndef _WIN32 return STDERR_FILENO; #else return GetStdHandle(STD_ERROR_HANDLE); #endif } /** * Automatic cleanup of resources. */ class AutoCloseFD { Descriptor fd; public: AutoCloseFD(); AutoCloseFD(Descriptor fd); AutoCloseFD(const AutoCloseFD & fd) = delete; AutoCloseFD(AutoCloseFD&& fd) noexcept; ~AutoCloseFD(); AutoCloseFD& operator =(const AutoCloseFD & fd) = delete; AutoCloseFD& operator =(AutoCloseFD&& fd); Descriptor get() const; explicit operator bool() const; Descriptor release(); void close(); /** * Perform a blocking fsync operation. */ void fsync() const; /** * Asynchronously flush to disk without blocking, if available on * the platform. This is just a performance optimization, and * fsync must be run later even if this is called. */ void startFsync() const; }; class Pipe { public: AutoCloseFD readSide, writeSide; void create(); void close(); }; #ifndef _WIN32 // Not needed on Windows, where we don't fork namespace unix { /** * Close all file descriptors except stdio fds (ie 0, 1, 2). * Good practice in child processes. */ void closeExtraFDs(); /** * Set the close-on-exec flag for the given file descriptor. */ void closeOnExec(Descriptor fd); } // namespace unix #endif #if defined(_WIN32) && _WIN32_WINNT >= 0x0600 namespace windows { Path handleToPath(Descriptor handle); std::wstring handleToFileName(Descriptor handle); } // namespace windows #endif MakeError(EndOfFile, Error); }
4,289
C++
.h
185
20.772973
105
0.720845
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,170
fmt.hh
NixOS_nix/src/libutil/fmt.hh
#pragma once ///@file #include <boost/format.hpp> #include <string> #include "ansicolor.hh" namespace nix { /** * A helper for writing `boost::format` expressions. * * These are equivalent: * * ``` * formatHelper(formatter, a_0, ..., a_n) * formatter % a_0 % ... % a_n * ``` * * With a single argument, `formatHelper(s)` is a no-op. */ template<class F> inline void formatHelper(F & f) { } template<class F, typename T, typename... Args> inline void formatHelper(F & f, const T & x, const Args & ... args) { // Interpolate one argument and then recurse. formatHelper(f % x, args...); } /** * Set the correct exceptions for `fmt`. */ inline void setExceptions(boost::format & fmt) { fmt.exceptions( boost::io::all_error_bits ^ boost::io::too_many_args_bit ^ boost::io::too_few_args_bit); } /** * A helper for writing a `boost::format` expression to a string. * * These are (roughly) equivalent: * * ``` * fmt(formatString, a_0, ..., a_n) * (boost::format(formatString) % a_0 % ... % a_n).str() * ``` * * However, when called with a single argument, the string is returned * unchanged. * * If you write code like this: * * ``` * std::cout << boost::format(stringFromUserInput) << std::endl; * ``` * * And `stringFromUserInput` contains formatting placeholders like `%s`, then * the code will crash at runtime. `fmt` helps you avoid this pitfall. */ inline std::string fmt(const std::string & s) { return s; } inline std::string fmt(std::string_view s) { return std::string(s); } inline std::string fmt(const char * s) { return s; } template<typename... Args> inline std::string fmt(const std::string & fs, const Args & ... args) { boost::format f(fs); setExceptions(f); formatHelper(f, args...); return f.str(); } /** * Values wrapped in this struct are printed in magenta. * * By default, arguments to `HintFmt` are printed in magenta. To avoid this, * either wrap the argument in `Uncolored` or add a specialization of * `HintFmt::operator%`. */ template <class T> struct Magenta { Magenta(const T &s) : value(s) {} const T & value; }; template <class T> std::ostream & operator<<(std::ostream & out, const Magenta<T> & y) { return out << ANSI_WARNING << y.value << ANSI_NORMAL; } /** * Values wrapped in this class are printed without coloring. * * Specifically, the color is reset to normal before printing the value. * * By default, arguments to `HintFmt` are printed in magenta (see `Magenta`). */ template <class T> struct Uncolored { Uncolored(const T & s) : value(s) {} const T & value; }; template <class T> std::ostream & operator<<(std::ostream & out, const Uncolored<T> & y) { return out << ANSI_NORMAL << y.value; } /** * A wrapper around `boost::format` which colors interpolated arguments in * magenta by default. */ class HintFmt { private: boost::format fmt; public: /** * Format the given string literally, without interpolating format * placeholders. */ HintFmt(const std::string & literal) : HintFmt("%s", Uncolored(literal)) { } static HintFmt fromFormatString(const std::string & format) { return HintFmt(boost::format(format)); } /** * Interpolate the given arguments into the format string. */ template<typename... Args> HintFmt(const std::string & format, const Args & ... args) : HintFmt(boost::format(format), args...) { } HintFmt(const HintFmt & hf) : fmt(hf.fmt) { } template<typename... Args> HintFmt(boost::format && fmt, const Args & ... args) : fmt(std::move(fmt)) { setExceptions(fmt); formatHelper(*this, args...); } template<class T> HintFmt & operator%(const T & value) { fmt % Magenta(value); return *this; } template<class T> HintFmt & operator%(const Uncolored<T> & value) { fmt % value.value; return *this; } HintFmt & operator=(HintFmt const & rhs) = default; std::string str() const { return fmt.str(); } }; std::ostream & operator<<(std::ostream & os, const HintFmt & hf); }
4,214
C++
.h
171
21.327485
77
0.645009
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,171
strings-inline.hh
NixOS_nix/src/libutil/strings-inline.hh
#pragma once #include "strings.hh" namespace nix { template<class C, class CharT> C basicTokenizeString(std::basic_string_view<CharT> s, std::basic_string_view<CharT> separators) { C result; auto pos = s.find_first_not_of(separators, 0); while (pos != s.npos) { auto end = s.find_first_of(separators, pos + 1); if (end == s.npos) end = s.size(); result.insert(result.end(), std::basic_string<CharT>(s, pos, end - pos)); pos = s.find_first_not_of(separators, end); } return result; } template<class C> C tokenizeString(std::string_view s, std::string_view separators) { return basicTokenizeString<C, char>(s, separators); } template<class C, class CharT> C basicSplitString(std::basic_string_view<CharT> s, std::basic_string_view<CharT> separators) { C result; size_t pos = 0; while (pos <= s.size()) { auto end = s.find_first_of(separators, pos); if (end == s.npos) end = s.size(); result.insert(result.end(), std::basic_string<CharT>(s, pos, end - pos)); pos = end + 1; } return result; } template<class C> C splitString(std::string_view s, std::string_view separators) { return basicSplitString<C, char>(s, separators); } template<class CharT, class C> std::basic_string<CharT> basicConcatStringsSep(const std::basic_string_view<CharT> sep, const C & ss) { size_t size = 0; bool tail = false; // need a cast to string_view since this is also called with Symbols for (const auto & s : ss) { if (tail) size += sep.size(); size += std::basic_string_view<CharT>{s}.size(); tail = true; } std::basic_string<CharT> s; s.reserve(size); tail = false; for (auto & i : ss) { if (tail) s += sep; s += i; tail = true; } return s; } template<class C> std::string concatStringsSep(const std::string_view sep, const C & ss) { return basicConcatStringsSep<char, C>(sep, ss); } template<class C> std::string dropEmptyInitThenConcatStringsSep(const std::string_view sep, const C & ss) { size_t size = 0; // TODO? remove to make sure we don't rely on the empty item ignoring behavior, // or just get rid of this function by understanding the remaining calls. // for (auto & i : ss) { // // Make sure we don't rely on the empty item ignoring behavior // assert(!i.empty()); // break; // } // need a cast to string_view since this is also called with Symbols for (const auto & s : ss) size += sep.size() + std::string_view(s).size(); std::string s; s.reserve(size); for (auto & i : ss) { if (s.size() != 0) s += sep; s += i; } return s; } } // namespace nix
2,822
C++
.h
93
25.419355
101
0.616348
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,172
references.hh
NixOS_nix/src/libutil/references.hh
#pragma once ///@file #include "hash.hh" namespace nix { class RefScanSink : public Sink { StringSet hashes; StringSet seen; std::string tail; public: RefScanSink(StringSet && hashes) : hashes(hashes) { } StringSet & getResult() { return seen; } void operator () (std::string_view data) override; }; struct RewritingSink : Sink { const StringMap rewrites; std::string::size_type maxRewriteSize; std::string prev; Sink & nextSink; uint64_t pos = 0; std::vector<uint64_t> matches; RewritingSink(const std::string & from, const std::string & to, Sink & nextSink); RewritingSink(const StringMap & rewrites, Sink & nextSink); void operator () (std::string_view data) override; void flush(); }; struct HashModuloSink : AbstractHashSink { HashSink hashSink; RewritingSink rewritingSink; HashModuloSink(HashAlgorithm ha, const std::string & modulus); void operator () (std::string_view data) override; HashResult finish() override; }; }
1,039
C++
.h
38
23.447368
85
0.70295
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,173
experimental-features.hh
NixOS_nix/src/libutil/experimental-features.hh
#pragma once ///@file #include "error.hh" #include "types.hh" #include <nlohmann/json_fwd.hpp> namespace nix { /** * The list of available experimental features. * * If you update this, don’t forget to also change the map defining * their string representation and documentation in the corresponding * `.cc` file as well. */ enum struct ExperimentalFeature { CaDerivations, ImpureDerivations, Flakes, FetchTree, NixCommand, GitHashing, RecursiveNix, NoUrlLiterals, FetchClosure, AutoAllocateUids, Cgroups, DaemonTrustOverride, DynamicDerivations, ParseTomlTimestamps, ReadOnlyLocalStore, LocalOverlayStore, ConfigurableImpureEnv, MountedSSHStore, VerifiedFetches, PipeOperators, }; /** * Just because writing `ExperimentalFeature::CaDerivations` is way too long */ using Xp = ExperimentalFeature; /** * Parse an experimental feature (enum value) from its name. Experimental * feature flag names are hyphenated and do not contain spaces. */ const std::optional<ExperimentalFeature> parseExperimentalFeature( const std::string_view & name); /** * Show the name of an experimental feature. This is the opposite of * parseExperimentalFeature(). */ std::string_view showExperimentalFeature(const ExperimentalFeature); /** * Compute the documentation of all experimental features. * * See `doc/manual` for how this information is used. */ nlohmann::json documentExperimentalFeatures(); /** * Shorthand for `str << showExperimentalFeature(feature)`. */ std::ostream & operator<<( std::ostream & str, const ExperimentalFeature & feature); /** * Parse a set of strings to the corresponding set of experimental * features, ignoring (but warning for) any unknown feature. */ std::set<ExperimentalFeature> parseFeatures(const std::set<std::string> &); /** * An experimental feature was required for some (experimental) * operation, but was not enabled. */ class MissingExperimentalFeature : public Error { public: /** * The experimental feature that was required but not enabled. */ ExperimentalFeature missingFeature; MissingExperimentalFeature(ExperimentalFeature missingFeature); }; /** * Semi-magic conversion to and from json. * See the nlohmann/json readme for more details. */ void to_json(nlohmann::json &, const ExperimentalFeature &); void from_json(const nlohmann::json &, ExperimentalFeature &); }
2,469
C++
.h
88
25.136364
76
0.753697
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,174
archive.hh
NixOS_nix/src/libutil/archive.hh
#pragma once ///@file #include "types.hh" #include "serialise.hh" #include "fs-sink.hh" namespace nix { /** * dumpPath creates a Nix archive of the specified path. * * @param path the file system data to dump. Dumping is recursive so if * this is a directory we dump it and all its children. * * @param [out] sink The serialised archive is fed into this sink. * * @param filter Can be used to skip certain files. * * The format is as follows: * * ``` * IF path points to a REGULAR FILE: * dump(path) = attrs( * [ ("type", "regular") * , ("contents", contents(path)) * ]) * * IF path points to a DIRECTORY: * dump(path) = attrs( * [ ("type", "directory") * , ("entries", concat(map(f, sort(entries(path))))) * ]) * where f(fn) = attrs( * [ ("name", fn) * , ("file", dump(path + "/" + fn)) * ]) * * where: * * attrs(as) = concat(map(attr, as)) + encN(0) * attrs((a, b)) = encS(a) + encS(b) * * encS(s) = encN(len(s)) + s + (padding until next 64-bit boundary) * * encN(n) = 64-bit little-endian encoding of n. * * contents(path) = the contents of a regular file. * * sort(strings) = lexicographic sort by 8-bit value (strcmp). * * entries(path) = the entries of a directory, without `.` and * `..`. * * `+` denotes string concatenation. * ``` */ void dumpPath(const Path & path, Sink & sink, PathFilter & filter = defaultPathFilter); /** * Same as dumpPath(), but returns the last modified date of the path. */ time_t dumpPathAndGetMtime(const Path & path, Sink & sink, PathFilter & filter = defaultPathFilter); /** * Dump an archive with a single file with these contents. * * @param s Contents of the file. */ void dumpString(std::string_view s, Sink & sink); void parseDump(FileSystemObjectSink & sink, Source & source); void restorePath(const std::filesystem::path & path, Source & source, bool startFsync = false); /** * Read a NAR from 'source' and write it to 'sink'. */ void copyNAR(Source & source, Sink & sink); inline constexpr std::string_view narVersionMagic1 = "nix-archive-1"; inline constexpr std::string_view caseHackSuffix = "~nix~case~hack~"; }
2,208
C++
.h
76
27.026316
95
0.649032
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,175
split.hh
NixOS_nix/src/libutil/split.hh
#pragma once ///@file #include <optional> #include <string_view> #include "util.hh" namespace nix { /** * If `separator` is found, we return the portion of the string before the * separator, and modify the string argument to contain only the part after the * separator. Otherwise, we return `std::nullopt`, and we leave the argument * string alone. */ static inline std::optional<std::string_view> splitPrefixTo(std::string_view & string, char separator) { auto sepInstance = string.find(separator); if (sepInstance != std::string_view::npos) { auto prefix = string.substr(0, sepInstance); string.remove_prefix(sepInstance+1); return prefix; } return std::nullopt; } static inline bool splitPrefix(std::string_view & string, std::string_view prefix) { bool res = hasPrefix(string, prefix); if (res) string.remove_prefix(prefix.length()); return res; } }
927
C++
.h
28
29.5
104
0.709315
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
11,176
lru-cache.hh
NixOS_nix/src/libutil/lru-cache.hh
#pragma once ///@file #include <cassert> #include <map> #include <list> #include <optional> namespace nix { /** * A simple least-recently used cache. Not thread-safe. */ template<typename Key, typename Value> class LRUCache { private: size_t capacity; // Stupid wrapper to get around circular dependency between Data // and LRU. struct LRUIterator; using Data = std::map<Key, std::pair<LRUIterator, Value>>; using LRU = std::list<typename Data::iterator>; struct LRUIterator { typename LRU::iterator it; }; Data data; LRU lru; public: LRUCache(size_t capacity) : capacity(capacity) { } /** * Insert or upsert an item in the cache. */ void upsert(const Key & key, const Value & value) { if (capacity == 0) return; erase(key); if (data.size() >= capacity) { /** * Retire the oldest item. */ auto oldest = lru.begin(); data.erase(*oldest); lru.erase(oldest); } auto res = data.emplace(key, std::make_pair(LRUIterator(), value)); assert(res.second); auto & i(res.first); auto j = lru.insert(lru.end(), i); i->second.first.it = j; } bool erase(const Key & key) { auto i = data.find(key); if (i == data.end()) return false; lru.erase(i->second.first.it); data.erase(i); return true; } /** * Look up an item in the cache. If it exists, it becomes the most * recently used item. * */ std::optional<Value> get(const Key & key) { auto i = data.find(key); if (i == data.end()) return {}; /** * Move this item to the back of the LRU list. */ lru.erase(i->second.first.it); auto j = lru.insert(lru.end(), i); i->second.first.it = j; return i->second.second; } size_t size() const { return data.size(); } void clear() { data.clear(); lru.clear(); } }; }
2,082
C++
.h
81
19.246914
75
0.559151
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,177
muxable-pipe.hh
NixOS_nix/src/libutil/muxable-pipe.hh
#pragma once ///@file #include "file-descriptor.hh" #ifdef _WIN32 # include "windows-async-pipe.hh" #endif #ifndef _WIN32 # include <poll.h> #else # include <ioapiset.h> # include "windows-error.hh" #endif namespace nix { /** * An "muxable pipe" is a type of pipe supporting endpoints that wait * for events on multiple pipes at once. * * On Unix, this is just a regular anonymous pipe. On Windows, this has * to be a named pipe because we need I/O Completion Ports to wait on * multiple pipes. */ using MuxablePipe = #ifndef _WIN32 Pipe #else windows::AsyncPipe #endif ; /** * Use pool() (Unix) / I/O Completion Ports (Windows) to wait for the * input side of any logger pipe to become `available'. Note that * `available' (i.e., non-blocking) includes EOF. */ struct MuxablePipePollState { #ifndef _WIN32 std::vector<struct pollfd> pollStatus; std::map<int, size_t> fdToPollStatus; #else OVERLAPPED_ENTRY oentries[0x20] = {0}; ULONG removed; bool gotEOF = false; #endif /** * Check for ready (Unix) / completed (Windows) operations */ void poll( #ifdef _WIN32 HANDLE ioport, #endif std::optional<unsigned int> timeout); using CommChannel = #ifndef _WIN32 Descriptor #else windows::AsyncPipe * #endif ; /** * Process for ready (Unix) / completed (Windows) operations, * calling the callbacks as needed. * * @param handleRead callback to be passed read data. * * @param handleEOF callback for when the `MuxablePipe` has closed. */ void iterate( std::set<CommChannel> & channels, std::function<void(Descriptor fd, std::string_view data)> handleRead, std::function<void(Descriptor fd)> handleEOF); }; }
1,788
C++
.h
72
21.305556
77
0.682298
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,178
position.hh
NixOS_nix/src/libutil/position.hh
#pragma once /** * @file * * @brief Pos and AbstractPos */ #include <cstdint> #include <string> #include <variant> #include "source-path.hh" namespace nix { /** * A position and an origin for that position (like a source file). */ struct Pos { uint32_t line = 0; uint32_t column = 0; struct Stdin { ref<std::string> source; bool operator==(const Stdin & rhs) const noexcept { return *source == *rhs.source; } std::strong_ordering operator<=>(const Stdin & rhs) const noexcept { return *source <=> *rhs.source; } }; struct String { ref<std::string> source; bool operator==(const String & rhs) const noexcept { return *source == *rhs.source; } std::strong_ordering operator<=>(const String & rhs) const noexcept { return *source <=> *rhs.source; } }; typedef std::variant<std::monostate, Stdin, String, SourcePath> Origin; Origin origin = std::monostate(); Pos() { } Pos(uint32_t line, uint32_t column, Origin origin) : line(line), column(column), origin(origin) { } Pos(Pos & other) = default; Pos(const Pos & other) = default; Pos(Pos && other) = default; Pos(const Pos * other); explicit operator bool() const { return line > 0; } operator std::shared_ptr<Pos>() const; /** * Return the contents of the source file. */ std::optional<std::string> getSource() const; void print(std::ostream & out, bool showOrigin) const; std::optional<LinesOfCode> getCodeLines() const; bool operator==(const Pos & rhs) const = default; auto operator<=>(const Pos & rhs) const = default; std::optional<std::string> getSnippetUpTo(const Pos & end) const; /** * Get the SourcePath, if the source was loaded from a file. */ std::optional<SourcePath> getSourcePath() const { return *std::get_if<SourcePath>(&origin); } struct LinesIterator { using difference_type = size_t; using value_type = std::string_view; using reference = const std::string_view &; using pointer = const std::string_view *; using iterator_category = std::input_iterator_tag; LinesIterator(): pastEnd(true) {} explicit LinesIterator(std::string_view input): input(input), pastEnd(input.empty()) { if (!pastEnd) bump(true); } LinesIterator & operator++() { bump(false); return *this; } LinesIterator operator++(int) { auto result = *this; ++*this; return result; } reference operator*() const { return curLine; } pointer operator->() const { return &curLine; } bool operator!=(const LinesIterator & other) const { return !(*this == other); } bool operator==(const LinesIterator & other) const { return (pastEnd && other.pastEnd) || (std::forward_as_tuple(input.size(), input.data()) == std::forward_as_tuple(other.input.size(), other.input.data())); } private: std::string_view input, curLine; bool pastEnd = false; void bump(bool atFirst); }; }; std::ostream & operator<<(std::ostream & str, const Pos & pos); }
3,342
C++
.h
96
27.78125
94
0.601987
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,179
compression.hh
NixOS_nix/src/libutil/compression.hh
#pragma once ///@file #include "ref.hh" #include "types.hh" #include "serialise.hh" #include <string> namespace nix { struct CompressionSink : BufferedSink, FinishSink { using BufferedSink::operator(); using BufferedSink::writeUnbuffered; using FinishSink::finish; }; std::string decompress(const std::string & method, std::string_view in); std::unique_ptr<FinishSink> makeDecompressionSink(const std::string & method, Sink & nextSink); std::string compress(const std::string & method, std::string_view in, const bool parallel = false, int level = -1); ref<CompressionSink> makeCompressionSink(const std::string & method, Sink & nextSink, const bool parallel = false, int level = -1); MakeError(UnknownCompressionMethod, Error); MakeError(CompressionError, Error); }
790
C++
.h
21
35.52381
115
0.770449
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,180
suggestions.hh
NixOS_nix/src/libutil/suggestions.hh
#pragma once ///@file #include "types.hh" #include <set> namespace nix { int levenshteinDistance(std::string_view first, std::string_view second); /** * A potential suggestion for the cli interface. */ class Suggestion { public: /// The smaller the better int distance; std::string suggestion; std::string to_string() const; bool operator ==(const Suggestion &) const = default; auto operator <=>(const Suggestion &) const = default; }; class Suggestions { public: std::set<Suggestion> suggestions; std::string to_string() const; Suggestions trim( int limit = 5, int maxDistance = 2 ) const; static Suggestions bestMatches ( const std::set<std::string> & allMatches, std::string_view query ); Suggestions& operator+=(const Suggestions & other); }; std::ostream & operator<<(std::ostream & str, const Suggestion &); std::ostream & operator<<(std::ostream & str, const Suggestions &); /** * Either a value of type `T`, or some suggestions */ template<typename T> class OrSuggestions { public: using Raw = std::variant<T, Suggestions>; Raw raw; T* operator ->() { return &**this; } T& operator *() { return std::get<T>(raw); } operator bool() const noexcept { return std::holds_alternative<T>(raw); } OrSuggestions(T t) : raw(t) { } OrSuggestions() : raw(Suggestions{}) { } static OrSuggestions<T> failed(const Suggestions & s) { auto res = OrSuggestions<T>(); res.raw = s; return res; } static OrSuggestions<T> failed() { return OrSuggestions<T>::failed(Suggestions{}); } const Suggestions & getSuggestions() { static Suggestions noSuggestions; if (const auto & suggestions = std::get_if<Suggestions>(&raw)) return *suggestions; else return noSuggestions; } }; }
1,997
C++
.h
82
19.256098
73
0.626653
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,181
checked-arithmetic.hh
NixOS_nix/src/libutil/checked-arithmetic.hh
#pragma once /** * @file * * Checked arithmetic with classes that make it hard to accidentally make something an unchecked operation. */ #include <compare> #include <concepts> // IWYU pragma: keep #include <exception> #include <ostream> #include <limits> #include <optional> #include <type_traits> namespace nix::checked { class DivideByZero : std::exception {}; /** * Numeric value enforcing checked arithmetic. Performing mathematical operations on such values will return a Result * type which needs to be checked. */ template<std::integral T> struct Checked { using Inner = T; // TODO: this must be a "trivial default constructor", which means it // cannot set the value to NOT DO UB on uninit. T value; Checked() = default; explicit Checked(T const value) : value{value} { } Checked(Checked<T> const & other) = default; Checked(Checked<T> && other) = default; Checked<T> & operator=(Checked<T> const & other) = default; std::strong_ordering operator<=>(Checked<T> const & other) const = default; std::strong_ordering operator<=>(T const & other) const { return value <=> other; } explicit operator T() const { return value; } enum class OverflowKind { NoOverflow, Overflow, DivByZero, }; class Result { T value; OverflowKind overflowed_; public: Result(T value, bool overflowed) : value{value} , overflowed_{overflowed ? OverflowKind::Overflow : OverflowKind::NoOverflow} { } Result(T value, OverflowKind overflowed) : value{value} , overflowed_{overflowed} { } bool operator==(Result other) const { return value == other.value && overflowed_ == other.overflowed_; } std::optional<T> valueChecked() const { if (overflowed_ != OverflowKind::NoOverflow) { return std::nullopt; } else { return value; } } /** * Returns the result as if the arithmetic were performed as wrapping arithmetic. * * \throws DivideByZero if the operation was a divide by zero. */ T valueWrapping() const { if (overflowed_ == OverflowKind::DivByZero) { throw DivideByZero{}; } return value; } bool overflowed() const { return overflowed_ == OverflowKind::Overflow; } bool divideByZero() const { return overflowed_ == OverflowKind::DivByZero; } }; Result operator+(Checked<T> const other) const { return (*this) + other.value; } Result operator+(T const other) const { T result; bool overflowed = __builtin_add_overflow(value, other, &result); return Result{result, overflowed}; } Result operator-(Checked<T> const other) const { return (*this) - other.value; } Result operator-(T const other) const { T result; bool overflowed = __builtin_sub_overflow(value, other, &result); return Result{result, overflowed}; } Result operator*(Checked<T> const other) const { return (*this) * other.value; } Result operator*(T const other) const { T result; bool overflowed = __builtin_mul_overflow(value, other, &result); return Result{result, overflowed}; } Result operator/(Checked<T> const other) const { return (*this) / other.value; } /** * Performs a checked division. * * If the right hand side is zero, the result is marked as a DivByZero and * valueWrapping will throw. */ Result operator/(T const other) const { constexpr T const minV = std::numeric_limits<T>::min(); // It's only possible to overflow with signed division since doing so // requires crossing the two's complement limits by MIN / -1 (since // two's complement has one more in range in the negative direction // than in the positive one). if (std::is_signed<T>() && (value == minV && other == -1)) { return Result{minV, true}; } else if (other == 0) { return Result{0, OverflowKind::DivByZero}; } else { T result = value / other; return Result{result, false}; } } }; template<std::integral T> std::ostream & operator<<(std::ostream & ios, Checked<T> v) { ios << v.value; return ios; } }
4,690
C++
.h
161
22.149068
117
0.596316
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,182
ansicolor.hh
NixOS_nix/src/libutil/ansicolor.hh
#pragma once /** * @file * * @brief Some ANSI escape sequences. */ namespace nix { #define ANSI_NORMAL "\e[0m" #define ANSI_BOLD "\e[1m" #define ANSI_FAINT "\e[2m" #define ANSI_ITALIC "\e[3m" #define ANSI_RED "\e[31;1m" #define ANSI_GREEN "\e[32;1m" #define ANSI_WARNING "\e[35;1m" #define ANSI_BLUE "\e[34;1m" #define ANSI_MAGENTA "\e[35;1m" #define ANSI_CYAN "\e[36;1m" }
381
C++
.h
18
19.777778
37
0.686111
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
11,183
json-impls.hh
NixOS_nix/src/libutil/json-impls.hh
#pragma once ///@file #include "nlohmann/json_fwd.hpp" // Following https://github.com/nlohmann/json#how-can-i-use-get-for-non-default-constructiblenon-copyable-types #define JSON_IMPL(TYPE) \ namespace nlohmann { \ using namespace nix; \ template <> \ struct adl_serializer<TYPE> { \ static TYPE from_json(const json & json); \ static void to_json(json & json, TYPE t); \ }; \ }
759
C++
.h
13
52.307692
111
0.365591
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,184
current-process.hh
NixOS_nix/src/libutil/current-process.hh
#pragma once ///@file #include <optional> #ifndef _WIN32 # include <sys/resource.h> #endif #include "types.hh" namespace nix { /** * If cgroups are active, attempt to calculate the number of CPUs available. * If cgroups are unavailable or if cpu.max is set to "max", return 0. */ unsigned int getMaxCPU(); /** * Change the stack size. */ void setStackSize(size_t stackSize); /** * Restore the original inherited Unix process context (such as signal * masks, stack size). * See unix::startSignalHandlerThread(), unix::saveSignalMask(). */ void restoreProcessContext(bool restoreMounts = true); /** * @return the path of the current executable. */ std::optional<Path> getSelfExe(); }
703
C++
.h
28
23.357143
76
0.742857
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,185
args.hh
NixOS_nix/src/libutil/args.hh
#pragma once ///@file #include <functional> #include <filesystem> #include <map> #include <memory> #include <optional> #include <nlohmann/json_fwd.hpp> #include "types.hh" #include "experimental-features.hh" #include "ref.hh" namespace nix { enum struct HashAlgorithm : char; enum struct HashFormat : int; class MultiCommand; class RootArgs; class AddCompletions; class Args { public: /** * Return a short one-line description of the command. */ virtual std::string description() { return ""; } virtual bool forceImpureByDefault() { return false; } /** * Return documentation about this command, in Markdown format. */ virtual std::string doc() { return ""; } /** * @brief Get the [base directory](https://nixos.org/manual/nix/unstable/glossary#gloss-base-directory) for the command. * * @return Generally the working directory, but in case of a shebang * interpreter, returns the directory of the script. * * This only returns the correct value after parseCmdline() has run. */ virtual Path getCommandBaseDir() const; protected: /** * The largest `size_t` is used to indicate the "any" arity, for * handlers/flags/arguments that accept an arbitrary number of * arguments. */ static const size_t ArityAny = std::numeric_limits<size_t>::max(); /** * Arguments (flags/options and positional) have a "handler" which is * caused when the argument is parsed. The handler has an arbitrary side * effect, including possible affect further command-line parsing. * * There are many constructors in order to support many shorthand * initializations, and this is used a lot. */ struct Handler { std::function<void(std::vector<std::string>)> fun; size_t arity; Handler() = default; Handler(std::function<void(std::vector<std::string>)> && fun) : fun(std::move(fun)) , arity(ArityAny) { } Handler(std::function<void()> && handler) : fun([handler{std::move(handler)}](std::vector<std::string>) { handler(); }) , arity(0) { } Handler(std::function<void(std::string)> && handler) : fun([handler{std::move(handler)}](std::vector<std::string> ss) { handler(std::move(ss[0])); }) , arity(1) { } Handler(std::function<void(std::string, std::string)> && handler) : fun([handler{std::move(handler)}](std::vector<std::string> ss) { handler(std::move(ss[0]), std::move(ss[1])); }) , arity(2) { } Handler(std::vector<std::string> * dest) : fun([dest](std::vector<std::string> ss) { *dest = ss; }) , arity(ArityAny) { } Handler(std::string * dest) : fun([dest](std::vector<std::string> ss) { *dest = ss[0]; }) , arity(1) { } Handler(std::optional<std::string> * dest) : fun([dest](std::vector<std::string> ss) { *dest = ss[0]; }) , arity(1) { } Handler(std::filesystem::path * dest) : fun([dest](std::vector<std::string> ss) { *dest = ss[0]; }) , arity(1) { } Handler(std::optional<std::filesystem::path> * dest) : fun([dest](std::vector<std::string> ss) { *dest = ss[0]; }) , arity(1) { } template<class T> Handler(T * dest, const T & val) : fun([dest, val](std::vector<std::string> ss) { *dest = val; }) , arity(0) { } template<class I> Handler(I * dest) : fun([dest](std::vector<std::string> ss) { *dest = string2IntWithUnitPrefix<I>(ss[0]); }) , arity(1) { } template<class I> Handler(std::optional<I> * dest) : fun([dest](std::vector<std::string> ss) { *dest = string2IntWithUnitPrefix<I>(ss[0]); }) , arity(1) { } }; /** * The basic function type of the completion callback. * * Used to define `CompleterClosure` and some common case completers * that individual flags/arguments can use. * * The `AddCompletions` that is passed is an interface to the state * stored as part of the root command */ using CompleterFun = void(AddCompletions &, size_t, std::string_view); /** * The closure type of the completion callback. * * This is what is actually stored as part of each Flag / Expected * Arg. */ using CompleterClosure = std::function<CompleterFun>; public: /** * Description of flags / options * * These are arguments like `-s` or `--long` that can (mostly) * appear in any order. */ struct Flag { using ptr = std::shared_ptr<Flag>; std::string longName; std::set<std::string> aliases; char shortName = 0; std::string description; std::string category; Strings labels; Handler handler; CompleterClosure completer; std::optional<ExperimentalFeature> experimentalFeature; }; protected: /** * Index of all registered "long" flag descriptions (flags like * `--long`). */ std::map<std::string, Flag::ptr> longFlags; /** * Index of all registered "short" flag descriptions (flags like * `-s`). */ std::map<char, Flag::ptr> shortFlags; /** * Process a single flag and its arguments, pulling from an iterator * of raw CLI args as needed. */ virtual bool processFlag(Strings::iterator & pos, Strings::iterator end); public: /** * Description of positional arguments * * These are arguments that do not start with a `-`, and for which * the order does matter. */ struct ExpectedArg { std::string label; bool optional = false; Handler handler; CompleterClosure completer; }; protected: /** * Queue of expected positional argument forms. * * Positional argument descriptions are inserted on the back. * * As positional arguments are passed, these are popped from the * front, until there are hopefully none left as all args that were * expected in fact were passed. */ std::list<ExpectedArg> expectedArgs; /** * List of processed positional argument forms. * * All items removed from `expectedArgs` are added here. After all * arguments were processed, this list should be exactly the same as * `expectedArgs` was before. * * This list is used to extend the lifetime of the argument forms. * If this is not done, some closures that reference the command * itself will segfault. */ std::list<ExpectedArg> processedArgs; /** * Process some positional arugments * * @param finish: We have parsed everything else, and these are the only * arguments left. Used because we accumulate some "pending args" we might * have left over. */ virtual bool processArgs(const Strings & args, bool finish); virtual Strings::iterator rewriteArgs(Strings & args, Strings::iterator pos) { return pos; } std::set<std::string> hiddenCategories; /** * Called after all command line flags before the first non-flag * argument (if any) have been processed. */ virtual void initialFlagsProcessed() {} public: void addFlag(Flag && flag); void removeFlag(const std::string & longName); void expectArgs(ExpectedArg && arg) { expectedArgs.emplace_back(std::move(arg)); } /** * Expect a string argument. */ void expectArg(const std::string & label, std::string * dest, bool optional = false) { expectArgs({ .label = label, .optional = optional, .handler = {dest} }); } /** * Expect a path argument. */ void expectArg(const std::string & label, std::filesystem::path * dest, bool optional = false) { expectArgs({ .label = label, .optional = optional, .handler = {dest} }); } /** * Expect 0 or more arguments. */ void expectArgs(const std::string & label, std::vector<std::string> * dest) { expectArgs({ .label = label, .handler = {dest} }); } static CompleterFun completePath; static CompleterFun completeDir; virtual nlohmann::json toJSON(); friend class MultiCommand; /** * The parent command, used if this is a subcommand. * * Invariant: An Args with a null parent must also be a RootArgs * * \todo this would probably be better in the CommandClass. * getRoot() could be an abstract method that peels off at most one * layer before recuring. */ MultiCommand * parent = nullptr; /** * Traverse parent pointers until we find the \ref RootArgs "root * arguments" object. */ RootArgs & getRoot(); }; /** * A command is an argument parser that can be executed by calling its * run() method. */ struct Command : virtual public Args { friend class MultiCommand; virtual ~Command() = default; /** * Entry point to the command */ virtual void run() = 0; using Category = int; static constexpr Category catDefault = 0; virtual std::optional<ExperimentalFeature> experimentalFeature(); virtual Category category() { return catDefault; } }; using Commands = std::map<std::string, std::function<ref<Command>()>>; /** * An argument parser that supports multiple subcommands, * i.e. `<command> <subcommand>`. */ class MultiCommand : virtual public Args { public: Commands commands; std::map<Command::Category, std::string> categories; /** * Selected command, if any. */ std::optional<std::pair<std::string, ref<Command>>> command; MultiCommand(std::string_view commandName, const Commands & commands); bool processFlag(Strings::iterator & pos, Strings::iterator end) override; bool processArgs(const Strings & args, bool finish) override; nlohmann::json toJSON() override; protected: std::string commandName = ""; }; Strings argvToStrings(int argc, char * * argv); struct Completion { std::string completion; std::string description; auto operator<=>(const Completion & other) const noexcept; }; /** * The abstract interface for completions callbacks * * The idea is to restrict the callback so it can only add additional * completions to the collection, or set the completion type. By making * it go through this interface, the callback cannot make any other * changes, or even view the completions / completion type that have * been set so far. */ class AddCompletions { public: /** * The type of completion we are collecting. */ enum class Type { Normal, Filenames, Attrs, }; /** * Set the type of the completions being collected * * \todo it should not be possible to change the type after it has been set. */ virtual void setType(Type type) = 0; /** * Add a single completion to the collection */ virtual void add(std::string completion, std::string description = "") = 0; }; Strings parseShebangContent(std::string_view s); }
11,622
C++
.h
360
25.847222
124
0.619005
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,186
file-system.hh
NixOS_nix/src/libutil/file-system.hh
#pragma once /** * @file * * Utiltities for working with the file sytem and file paths. */ #include "types.hh" #include "error.hh" #include "logging.hh" #include "file-descriptor.hh" #include "file-path.hh" #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #ifdef _WIN32 # include <windef.h> #endif #include <signal.h> #include <atomic> #include <functional> #include <map> #include <sstream> #include <optional> /** * Polyfill for MinGW * * Windows does in fact support symlinks, but the C runtime interfaces predate this. * * @todo get rid of this, and stop using `stat` when we want `lstat` too. */ #ifndef S_ISLNK # define S_ISLNK(m) false #endif namespace nix { struct Sink; struct Source; /** * @return An absolutized path, resolving paths relative to the * specified directory, or the current directory otherwise. The path * is also canonicalised. * * In the process of being deprecated for `std::filesystem::absolute`. */ Path absPath(PathView path, std::optional<PathView> dir = {}, bool resolveSymlinks = false); inline Path absPath(const Path & path, std::optional<PathView> dir = {}, bool resolveSymlinks = false) { return absPath(PathView{path}, dir, resolveSymlinks); } std::filesystem::path absPath(const std::filesystem::path & path, bool resolveSymlinks = false); /** * Canonicalise a path by removing all `.` or `..` components and * double or trailing slashes. Optionally resolves all symlink * components such that each component of the resulting path is *not* * a symbolic link. * * In the process of being deprecated for * `std::filesystem::path::lexically_normal` (for the `resolveSymlinks = * false` case), and `std::filesystem::weakly_canonical` (for the * `resolveSymlinks = true` case). */ Path canonPath(PathView path, bool resolveSymlinks = false); /** * @return The directory part of the given canonical path, i.e., * everything before the final `/`. If the path is the root or an * immediate child thereof (e.g., `/foo`), this means `/` * is returned. * * In the process of being deprecated for * `std::filesystem::path::parent_path`. */ Path dirOf(const PathView path); /** * @return the base name of the given canonical path, i.e., everything * following the final `/` (trailing slashes are removed). * * In the process of being deprecated for * `std::filesystem::path::filename`. */ std::string_view baseNameOf(std::string_view path); /** * Check whether 'path' is a descendant of 'dir'. Both paths must be * canonicalized. */ bool isInDir(std::string_view path, std::string_view dir); /** * Check whether 'path' is equal to 'dir' or a descendant of * 'dir'. Both paths must be canonicalized. */ bool isDirOrInDir(std::string_view path, std::string_view dir); /** * Get status of `path`. */ struct stat stat(const Path & path); struct stat lstat(const Path & path); /** * `lstat` the given path if it exists. * @return std::nullopt if the path doesn't exist, or an optional containing the result of `lstat` otherwise */ std::optional<struct stat> maybeLstat(const Path & path); /** * @return true iff the given path exists. * * In the process of being deprecated for `fs::symlink_exists`. */ bool pathExists(const Path & path); namespace fs { /** * ``` * symlink_exists(p) = std::filesystem::exists(std::filesystem::symlink_status(p)) * ``` * Missing convenience analogous to * ``` * std::filesystem::exists(p) = std::filesystem::exists(std::filesystem::status(p)) * ``` */ inline bool symlink_exists(const std::filesystem::path & path) { return std::filesystem::exists(std::filesystem::symlink_status(path)); } } // namespace fs /** * A version of pathExists that returns false on a permission error. * Useful for inferring default paths across directories that might not * be readable. * @return true iff the given path can be accessed and exists */ bool pathAccessible(const std::filesystem::path & path); /** * Read the contents (target) of a symbolic link. The result is not * in any way canonicalised. * * In the process of being deprecated for * `std::filesystem::read_symlink`. */ Path readLink(const Path & path); /** * Open a `Descriptor` with read-only access to the given directory. */ Descriptor openDirectory(const std::filesystem::path & path); /** * Read the contents of a file into a string. */ std::string readFile(const Path & path); std::string readFile(const std::filesystem::path & path); void readFile(const Path & path, Sink & sink); /** * Write a string to a file. */ void writeFile(const Path & path, std::string_view s, mode_t mode = 0666, bool sync = false); static inline void writeFile(const std::filesystem::path & path, std::string_view s, mode_t mode = 0666, bool sync = false) { return writeFile(path.string(), s, mode, sync); } void writeFile(const Path & path, Source & source, mode_t mode = 0666, bool sync = false); static inline void writeFile(const std::filesystem::path & path, Source & source, mode_t mode = 0666, bool sync = false) { return writeFile(path.string(), source, mode, sync); } /** * Flush a path's parent directory to disk. */ void syncParent(const Path & path); /** * Flush a file or entire directory tree to disk. */ void recursiveSync(const Path & path); /** * Delete a path; i.e., in the case of a directory, it is deleted * recursively. It's not an error if the path does not exist. The * second variant returns the number of bytes and blocks freed. */ void deletePath(const std::filesystem::path & path); void deletePath(const std::filesystem::path & path, uint64_t & bytesFreed); /** * Create a directory and all its parents, if necessary. * * In the process of being deprecated for * `std::filesystem::create_directories`. */ void createDirs(const Path & path); inline void createDirs(PathView path) { return createDirs(Path(path)); } /** * Create a single directory. */ void createDir(const Path & path, mode_t mode = 0755); /** * Set the access and modification times of the given path, not * following symlinks. * * @param accessedTime Specified in seconds. * * @param modificationTime Specified in seconds. * * @param isSymlink Whether the file in question is a symlink. Used for * fallback code where we don't have `lutimes` or similar. if * `std::optional` is passed, the information will be recomputed if it * is needed. Race conditions are possible so be careful! */ void setWriteTime( const std::filesystem::path & path, time_t accessedTime, time_t modificationTime, std::optional<bool> isSymlink = std::nullopt); /** * Convenience wrapper that takes all arguments from the `struct stat`. */ void setWriteTime(const std::filesystem::path & path, const struct stat & st); /** * Create a symlink. * * In the process of being deprecated for * `std::filesystem::create_symlink`. */ void createSymlink(const Path & target, const Path & link); /** * Atomically create or replace a symlink. */ void replaceSymlink(const std::filesystem::path & target, const std::filesystem::path & link); inline void replaceSymlink(const Path & target, const Path & link) { return replaceSymlink(std::filesystem::path{target}, std::filesystem::path{link}); } /** * Similar to 'renameFile', but fallback to a copy+remove if `src` and `dst` * are on a different filesystem. * * Beware that this might not be atomic because of the copy that happens behind * the scenes */ void moveFile(const Path & src, const Path & dst); /** * Recursively copy the content of `oldPath` to `newPath`. If `andDelete` is * `true`, then also remove `oldPath` (making this equivalent to `moveFile`, but * with the guaranty that the destination will be “fresh”, with no stale inode * or file descriptor pointing to it). */ void copyFile(const std::filesystem::path & from, const std::filesystem::path & to, bool andDelete); /** * Automatic cleanup of resources. */ class AutoDelete { std::filesystem::path _path; bool del; bool recursive; public: AutoDelete(); AutoDelete(const std::filesystem::path & p, bool recursive = true); ~AutoDelete(); void cancel(); void reset(const std::filesystem::path & p, bool recursive = true); const std::filesystem::path & path() const { return _path; } PathViewNG view() const { return _path; } operator const std::filesystem::path & () const { return _path; } operator PathViewNG () const { return _path; } }; struct DIRDeleter { void operator()(DIR * dir) const { closedir(dir); } }; typedef std::unique_ptr<DIR, DIRDeleter> AutoCloseDir; /** * Create a temporary directory. */ Path createTempDir(const Path & tmpRoot = "", const Path & prefix = "nix", bool includePid = true, bool useGlobalCounter = true, mode_t mode = 0755); /** * Create a temporary file, returning a file handle and its path. */ std::pair<AutoCloseFD, Path> createTempFile(const Path & prefix = "nix"); /** * Return `TMPDIR`, or the default temporary directory if unset or empty. */ Path defaultTempDir(); /** * Interpret `exe` as a location in the ambient file system and return * whether it resolves to a file that is executable. */ bool isExecutableFileAmbient(const std::filesystem::path & exe); /** * Used in various places. */ typedef std::function<bool(const Path & path)> PathFilter; extern PathFilter defaultPathFilter; }
9,470
C++
.h
295
29.99661
123
0.720961
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,187
closure.hh
NixOS_nix/src/libutil/closure.hh
#pragma once ///@file #include <set> #include <future> #include "sync.hh" using std::set; namespace nix { template<typename T> using GetEdgesAsync = std::function<void(const T &, std::function<void(std::promise<set<T>> &)>)>; template<typename T> void computeClosure( const set<T> startElts, set<T> & res, GetEdgesAsync<T> getEdgesAsync ) { struct State { size_t pending; set<T> & res; std::exception_ptr exc; }; Sync<State> state_(State{0, res, 0}); std::function<void(const T &)> enqueue; std::condition_variable done; enqueue = [&](const T & current) -> void { { auto state(state_.lock()); if (state->exc) return; if (!state->res.insert(current).second) return; state->pending++; } getEdgesAsync(current, [&](std::promise<set<T>> & prom) { try { auto children = prom.get_future().get(); for (auto & child : children) enqueue(child); { auto state(state_.lock()); assert(state->pending); if (!--state->pending) done.notify_one(); } } catch (...) { auto state(state_.lock()); if (!state->exc) state->exc = std::current_exception(); assert(state->pending); if (!--state->pending) done.notify_one(); }; }); }; for (auto & startElt : startElts) enqueue(startElt); { auto state(state_.lock()); while (state->pending) state.wait(done); if (state->exc) std::rethrow_exception(state->exc); } } }
1,738
C++
.h
59
20.847458
98
0.520408
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,188
executable-path.hh
NixOS_nix/src/libutil/executable-path.hh
#pragma once ///@file #include "file-system.hh" namespace nix { MakeError(ExecutableLookupError, Error); /** * @todo rename, it is not just good for execuatable paths, but also * other lists of paths. */ struct ExecutablePath { std::vector<std::filesystem::path> directories; constexpr static const OsChar separator = #ifdef WIN32 L';' #else ':' #endif ; /** * Parse `path` into a list of paths. * * On Unix we split on `:`, on Windows we split on `;`. * * For Unix, this is according to the POSIX spec for `PATH`. * https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03 */ static ExecutablePath parse(const OsString & path); /** * Load the `PATH` environment variable and `parse` it. */ static ExecutablePath load(); /** * Opposite of `parse` */ OsString render() const; /** * Search for an executable. * * For Unix, this is according to the POSIX spec for `PATH`. * https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03 * * @param exe This must just be a name, and not contain any `/` (or * `\` on Windows). in case it does, per the spec no lookup should * be perfomed, and the path (it is not just a file name) as is. * This is the caller's respsonsibility. * * This is a pure function, except for the default `isExecutable` * argument, which uses the ambient file system to check if a file is * executable (and exists). * * @return path to a resolved executable */ std::optional<std::filesystem::path> findName( const OsString & exe, std::function<bool(const std::filesystem::path &)> isExecutableFile = isExecutableFileAmbient) const; /** * Like the `findName` but also allows a file path as input. * * This implements the full POSIX spec: if the path is just a name, * it searches like the above. Otherwise, it returns the path as is. * If (in the name case) the search fails, an exception is thrown. */ std::filesystem::path findPath( const std::filesystem::path & exe, std::function<bool(const std::filesystem::path &)> isExecutable = isExecutableFileAmbient) const; bool operator==(const ExecutablePath &) const = default; }; } // namespace nix
2,400
C++
.h
69
29.608696
109
0.658473
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,189
ref.hh
NixOS_nix/src/libutil/ref.hh
#pragma once ///@file #include <memory> #include <stdexcept> namespace nix { /** * A simple non-nullable reference-counted pointer. Actually a wrapper * around std::shared_ptr that prevents null constructions. */ template<typename T> class ref { private: std::shared_ptr<T> p; public: explicit ref(const std::shared_ptr<T> & p) : p(p) { if (!p) throw std::invalid_argument("null pointer cast to ref"); } explicit ref(T * p) : p(p) { if (!p) throw std::invalid_argument("null pointer cast to ref"); } T* operator ->() const { return &*p; } T& operator *() const { return *p; } operator std::shared_ptr<T> () const { return p; } std::shared_ptr<T> get_ptr() const { return p; } template<typename T2> ref<T2> cast() const { return ref<T2>(std::dynamic_pointer_cast<T2>(p)); } template<typename T2> std::shared_ptr<T2> dynamic_pointer_cast() const { return std::dynamic_pointer_cast<T2>(p); } template<typename T2> operator ref<T2> () const { return ref<T2>((std::shared_ptr<T2>) p); } bool operator == (const ref<T> & other) const { return p == other.p; } bool operator != (const ref<T> & other) const { return p != other.p; } auto operator <=> (const ref<T> & other) const { return p <=> other.p; } private: template<typename T2, typename... Args> friend ref<T2> make_ref(Args&&... args); }; template<typename T, typename... Args> inline ref<T> make_ref(Args&&... args) { auto p = std::make_shared<T>(std::forward<Args>(args)...); return ref<T>(p); } }
1,791
C++
.h
83
16.481928
70
0.573207
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,190
unix-domain-socket.hh
NixOS_nix/src/libutil/unix-domain-socket.hh
#pragma once ///@file #include "types.hh" #include "file-descriptor.hh" #ifdef _WIN32 # include <winsock2.h> #endif #include <unistd.h> namespace nix { /** * Create a Unix domain socket. */ AutoCloseFD createUnixDomainSocket(); /** * Create a Unix domain socket in listen mode. */ AutoCloseFD createUnixDomainSocket(const Path & path, mode_t mode); /** * Often we want to use `Descriptor`, but Windows makes a slightly * stronger file descriptor vs socket distinction, at least at the level * of C types. */ using Socket = #ifdef _WIN32 SOCKET #else int #endif ; #ifdef _WIN32 /** * Windows gives this a different name */ # define SHUT_WR SD_SEND # define SHUT_RDWR SD_BOTH #endif /** * Convert a `Socket` to a `Descriptor` * * This is a no-op except on Windows. */ static inline Socket toSocket(Descriptor fd) { #ifdef _WIN32 return reinterpret_cast<Socket>(fd); #else return fd; #endif } /** * Convert a `Socket` to a `Descriptor` * * This is a no-op except on Windows. */ static inline Descriptor fromSocket(Socket fd) { #ifdef _WIN32 return reinterpret_cast<Descriptor>(fd); #else return fd; #endif } /** * Bind a Unix domain socket to a path. */ void bind(Socket fd, const std::string & path); /** * Connect to a Unix domain socket. */ void connect(Socket fd, const std::string & path); }
1,359
C++
.h
71
17.267606
72
0.718652
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,191
sync.hh
NixOS_nix/src/libutil/sync.hh
#pragma once ///@file #include <cstdlib> #include <mutex> #include <shared_mutex> #include <condition_variable> #include <cassert> #include "error.hh" namespace nix { /** * This template class ensures synchronized access to a value of type * T. It is used as follows: * * struct Data { int x; ... }; * * Sync<Data> data; * * { * auto data_(data.lock()); * data_->x = 123; * } * * Here, "data" is automatically unlocked when "data_" goes out of * scope. */ template<class T, class M, class WL, class RL> class SyncBase { private: M mutex; T data; public: SyncBase() { } SyncBase(const T & data) : data(data) { } SyncBase(T && data) noexcept : data(std::move(data)) { } template<class L> class Lock { protected: SyncBase * s; L lk; friend SyncBase; Lock(SyncBase * s) : s(s), lk(s->mutex) { } public: Lock(Lock && l) : s(l.s) { unreachable(); } Lock(const Lock & l) = delete; ~Lock() { } void wait(std::condition_variable & cv) { assert(s); cv.wait(lk); } template<class Rep, class Period> std::cv_status wait_for(std::condition_variable & cv, const std::chrono::duration<Rep, Period> & duration) { assert(s); return cv.wait_for(lk, duration); } template<class Rep, class Period, class Predicate> bool wait_for(std::condition_variable & cv, const std::chrono::duration<Rep, Period> & duration, Predicate pred) { assert(s); return cv.wait_for(lk, duration, pred); } template<class Clock, class Duration> std::cv_status wait_until(std::condition_variable & cv, const std::chrono::time_point<Clock, Duration> & duration) { assert(s); return cv.wait_until(lk, duration); } }; struct WriteLock : Lock<WL> { T * operator -> () { return &WriteLock::s->data; } T & operator * () { return WriteLock::s->data; } }; /** * Acquire write (exclusive) access to the inner value. */ WriteLock lock() { return WriteLock(this); } struct ReadLock : Lock<RL> { const T * operator -> () { return &ReadLock::s->data; } const T & operator * () { return ReadLock::s->data; } }; /** * Acquire read access to the inner value. When using * `std::shared_mutex`, this will use a shared lock. */ ReadLock readLock() const { return ReadLock(const_cast<SyncBase *>(this)); } }; template<class T> using Sync = SyncBase<T, std::mutex, std::unique_lock<std::mutex>, std::unique_lock<std::mutex>>; template<class T> using SharedSync = SyncBase<T, std::shared_mutex, std::unique_lock<std::shared_mutex>, std::shared_lock<std::shared_mutex>>; }
2,915
C++
.h
100
23.21
124
0.582767
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,192
url-parts.hh
NixOS_nix/src/libutil/url-parts.hh
#pragma once ///@file #include <string> #include <regex> namespace nix { // URI stuff. const static std::string pctEncoded = "(?:%[0-9a-fA-F][0-9a-fA-F])"; const static std::string schemeNameRegex = "(?:[a-z][a-z0-9+.-]*)"; const static std::string ipv6AddressSegmentRegex = "[0-9a-fA-F:]+(?:%\\w+)?"; const static std::string ipv6AddressRegex = "(?:\\[" + ipv6AddressSegmentRegex + "\\]|" + ipv6AddressSegmentRegex + ")"; const static std::string unreservedRegex = "(?:[a-zA-Z0-9-._~])"; const static std::string subdelimsRegex = "(?:[!$&'\"()*+,;=])"; const static std::string hostnameRegex = "(?:(?:" + unreservedRegex + "|" + pctEncoded + "|" + subdelimsRegex + ")*)"; const static std::string hostRegex = "(?:" + ipv6AddressRegex + "|" + hostnameRegex + ")"; const static std::string userRegex = "(?:(?:" + unreservedRegex + "|" + pctEncoded + "|" + subdelimsRegex + "|:)*)"; const static std::string authorityRegex = "(?:" + userRegex + "@)?" + hostRegex + "(?::[0-9]+)?"; const static std::string pcharRegex = "(?:" + unreservedRegex + "|" + pctEncoded + "|" + subdelimsRegex + "|[:@])"; const static std::string queryRegex = "(?:" + pcharRegex + "|[/? \"])*"; const static std::string fragmentRegex = "(?:" + pcharRegex + "|[/? \"^])*"; const static std::string segmentRegex = "(?:" + pcharRegex + "*)"; const static std::string absPathRegex = "(?:(?:/" + segmentRegex + ")*/?)"; const static std::string pathRegex = "(?:" + segmentRegex + "(?:/" + segmentRegex + ")*/?)"; /// A Git ref (i.e. branch or tag name). /// \todo check that this is correct. /// This regex incomplete. See https://git-scm.com/docs/git-check-ref-format const static std::string refRegexS = "[a-zA-Z0-9@][a-zA-Z0-9_.\\/@+-]*"; extern std::regex refRegex; /// Instead of defining what a good Git Ref is, we define what a bad Git Ref is /// This is because of the definition of a ref in refs.c in https://github.com/git/git /// See tests/functional/fetchGitRefs.sh for the full definition const static std::string badGitRefRegexS = "//|^[./]|/\\.|\\.\\.|[[:cntrl:][:space:]:?^~\[]|\\\\|\\*|\\.lock$|\\.lock/|@\\{|[/.]$|^@$|^$"; extern std::regex badGitRefRegex; /// A Git revision (a SHA-1 commit hash). const static std::string revRegexS = "[0-9a-fA-F]{40}"; extern std::regex revRegex; /// A ref or revision, or a ref followed by a revision. const static std::string refAndOrRevRegex = "(?:(" + revRegexS + ")|(?:(" + refRegexS + ")(?:/(" + revRegexS + "))?))"; }
2,455
C++
.h
38
63.394737
138
0.624325
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,193
source-path.hh
NixOS_nix/src/libutil/source-path.hh
#pragma once /** * @file * * @brief SourcePath */ #include "ref.hh" #include "canon-path.hh" #include "source-accessor.hh" #include "std-hash.hh" namespace nix { /** * An abstraction for accessing source files during * evaluation. Currently, it's just a wrapper around `CanonPath` that * accesses files in the regular filesystem, but in the future it will * support fetching files in other ways. */ struct SourcePath { ref<SourceAccessor> accessor; CanonPath path; SourcePath(ref<SourceAccessor> accessor, CanonPath path = CanonPath::root) : accessor(std::move(accessor)) , path(std::move(path)) { } std::string_view baseName() const; /** * Construct the parent of this `SourcePath`. Aborts if `this` * denotes the root. */ SourcePath parent() const; /** * If this `SourcePath` denotes a regular file (not a symlink), * return its contents; otherwise throw an error. */ std::string readFile() const; void readFile( Sink & sink, std::function<void(uint64_t)> sizeCallback = [](uint64_t size){}) const { return accessor->readFile(path, sink, sizeCallback); } /** * Return whether this `SourcePath` denotes a file (of any type) * that exists */ bool pathExists() const; /** * Return stats about this `SourcePath`, or throw an exception if * it doesn't exist. */ SourceAccessor::Stat lstat() const; /** * Return stats about this `SourcePath`, or std::nullopt if it * doesn't exist. */ std::optional<SourceAccessor::Stat> maybeLstat() const; /** * If this `SourcePath` denotes a directory (not a symlink), * return its directory entries; otherwise throw an error. */ SourceAccessor::DirEntries readDirectory() const; /** * If this `SourcePath` denotes a symlink, return its target; * otherwise throw an error. */ std::string readLink() const; /** * Dump this `SourcePath` to `sink` as a NAR archive. */ void dumpPath( Sink & sink, PathFilter & filter = defaultPathFilter) const; /** * Return the location of this path in the "real" filesystem, if * it has a physical location. */ std::optional<std::filesystem::path> getPhysicalPath() const; std::string to_string() const; /** * Append a `CanonPath` to this path. */ SourcePath operator / (const CanonPath & x) const; /** * Append a single component `c` to this path. `c` must not * contain a slash. A slash is implicitly added between this path * and `c`. */ SourcePath operator / (std::string_view c) const; bool operator==(const SourcePath & x) const noexcept; std::strong_ordering operator<=>(const SourcePath & x) const noexcept; /** * Convenience wrapper around `SourceAccessor::resolveSymlinks()`. */ SourcePath resolveSymlinks( SymlinkResolution mode = SymlinkResolution::Full) const { return {accessor, accessor->resolveSymlinks(path, mode)}; } friend class std::hash<nix::SourcePath>; }; std::ostream & operator << (std::ostream & str, const SourcePath & path); } template<> struct std::hash<nix::SourcePath> { std::size_t operator()(const nix::SourcePath & s) const noexcept { std::size_t hash = 0; hash_combine(hash, s.accessor->number, s.path); return hash; } };
3,471
C++
.h
111
26.216216
79
0.652578
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,194
url.hh
NixOS_nix/src/libutil/url.hh
#pragma once ///@file #include "error.hh" namespace nix { struct ParsedURL { std::string url; /// URL without query/fragment std::string base; std::string scheme; std::optional<std::string> authority; std::string path; std::map<std::string, std::string> query; std::string fragment; std::string to_string() const; bool operator ==(const ParsedURL & other) const noexcept; /** * Remove `.` and `..` path elements. */ ParsedURL canonicalise(); }; MakeError(BadURL, Error); std::string percentDecode(std::string_view in); std::string percentEncode(std::string_view s, std::string_view keep=""); std::map<std::string, std::string> decodeQuery(const std::string & query); std::string encodeQuery(const std::map<std::string, std::string> & query); ParsedURL parseURL(const std::string & url); /** * Although that’s not really standardized anywhere, an number of tools * use a scheme of the form 'x+y' in urls, where y is the “transport layer” * scheme, and x is the “application layer” scheme. * * For example git uses `git+https` to designate remotes using a Git * protocol over http. */ struct ParsedUrlScheme { std::optional<std::string_view> application; std::string_view transport; }; ParsedUrlScheme parseUrlScheme(std::string_view scheme); /* Detects scp-style uris (e.g. git@github.com:NixOS/nix) and fixes them by removing the `:` and assuming a scheme of `ssh://`. Also changes absolute paths into file:// URLs. */ std::string fixGitURL(const std::string & url); /** * Whether a string is valid as RFC 3986 scheme name. * Colon `:` is part of the URI; not the scheme name, and therefore rejected. * See https://www.rfc-editor.org/rfc/rfc3986#section-3.1 * * Does not check whether the scheme is understood, as that's context-dependent. */ bool isValidSchemeName(std::string_view scheme); }
1,905
C++
.h
53
32.849057
80
0.715225
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,195
compute-levels.hh
NixOS_nix/src/libutil/compute-levels.hh
#pragma once ///@file #include "types.hh" namespace nix { StringSet computeLevels(); }
91
C++
.h
6
13.5
26
0.765432
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,196
xml-writer.hh
NixOS_nix/src/libutil/xml-writer.hh
#pragma once ///@file #include <iostream> #include <string> #include <list> #include <map> namespace nix { typedef std::map<std::string, std::string> XMLAttrs; class XMLWriter { private: std::ostream & output; bool indent; bool closed; std::list<std::string> pendingElems; public: XMLWriter(bool indent, std::ostream & output); ~XMLWriter(); void close(); void openElement(std::string_view name, const XMLAttrs & attrs = XMLAttrs()); void closeElement(); void writeEmptyElement(std::string_view name, const XMLAttrs & attrs = XMLAttrs()); private: void writeAttrs(const XMLAttrs & attrs); void indent_(size_t depth); }; class XMLOpenElement { private: XMLWriter & writer; public: XMLOpenElement(XMLWriter & writer, std::string_view name, const XMLAttrs & attrs = XMLAttrs()) : writer(writer) { writer.openElement(name, attrs); } ~XMLOpenElement() { writer.closeElement(); } }; }
1,024
C++
.h
45
18.533333
61
0.672234
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
11,197
config-impl.hh
NixOS_nix/src/libutil/config-impl.hh
#pragma once /** * @file * * Template implementations (as opposed to mere declarations). * * This file is an example of the "impl.hh" pattern. See the * contributing guide. * * One only needs to include this when one is declaring a * `BaseClass<CustomType>` setting, or as derived class of such an * instantiation. */ #include "config.hh" namespace nix { template<> struct BaseSetting<Strings>::trait { static constexpr bool appendable = true; }; template<> struct BaseSetting<StringSet>::trait { static constexpr bool appendable = true; }; template<> struct BaseSetting<StringMap>::trait { static constexpr bool appendable = true; }; template<> struct BaseSetting<std::set<ExperimentalFeature>>::trait { static constexpr bool appendable = true; }; template<typename T> struct BaseSetting<T>::trait { static constexpr bool appendable = false; }; template<typename T> bool BaseSetting<T>::isAppendable() { return trait::appendable; } template<> void BaseSetting<Strings>::appendOrSet(Strings newValue, bool append); template<> void BaseSetting<StringSet>::appendOrSet(StringSet newValue, bool append); template<> void BaseSetting<StringMap>::appendOrSet(StringMap newValue, bool append); template<> void BaseSetting<std::set<ExperimentalFeature>>::appendOrSet(std::set<ExperimentalFeature> newValue, bool append); template<typename T> void BaseSetting<T>::appendOrSet(T newValue, bool append) { static_assert( !trait::appendable, "using default `appendOrSet` implementation with an appendable type"); assert(!append); value = std::move(newValue); } template<typename T> void BaseSetting<T>::set(const std::string & str, bool append) { if (experimentalFeatureSettings.isEnabled(experimentalFeature)) appendOrSet(parse(str), append); else { assert(experimentalFeature); warn("Ignoring setting '%s' because experimental feature '%s' is not enabled", name, showExperimentalFeature(*experimentalFeature)); } } template<> void BaseSetting<bool>::convertToArg(Args & args, const std::string & category); template<typename T> void BaseSetting<T>::convertToArg(Args & args, const std::string & category) { args.addFlag({ .longName = name, .aliases = aliases, .description = fmt("Set the `%s` setting.", name), .category = category, .labels = {"value"}, .handler = {[this](std::string s) { overridden = true; set(s); }}, .experimentalFeature = experimentalFeature, }); if (isAppendable()) args.addFlag({ .longName = "extra-" + name, .aliases = aliases, .description = fmt("Append to the `%s` setting.", name), .category = category, .labels = {"value"}, .handler = {[this](std::string s) { overridden = true; set(s, true); }}, .experimentalFeature = experimentalFeature, }); } #define DECLARE_CONFIG_SERIALISER(TY) \ template<> TY BaseSetting< TY >::parse(const std::string & str) const; \ template<> std::string BaseSetting< TY >::to_string() const; DECLARE_CONFIG_SERIALISER(std::string) DECLARE_CONFIG_SERIALISER(std::optional<std::string>) DECLARE_CONFIG_SERIALISER(bool) DECLARE_CONFIG_SERIALISER(Strings) DECLARE_CONFIG_SERIALISER(StringSet) DECLARE_CONFIG_SERIALISER(StringMap) DECLARE_CONFIG_SERIALISER(std::set<ExperimentalFeature>) template<typename T> T BaseSetting<T>::parse(const std::string & str) const { static_assert(std::is_integral<T>::value, "Integer required."); try { return string2IntWithUnitPrefix<T>(str); } catch (...) { throw UsageError("setting '%s' has invalid value '%s'", name, str); } } template<typename T> std::string BaseSetting<T>::to_string() const { static_assert(std::is_integral<T>::value, "Integer required."); return std::to_string(value); } }
3,932
C++
.h
117
29.547009
125
0.701264
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,198
chunked-vector.hh
NixOS_nix/src/libutil/chunked-vector.hh
#pragma once ///@file #include <cstdint> #include <cstdlib> #include <vector> #include <limits> #include "error.hh" namespace nix { /** * Provides an indexable container like vector<> with memory overhead * guarantees like list<> by allocating storage in chunks of ChunkSize * elements instead of using a contiguous memory allocation like vector<> * does. Not using a single vector that is resized reduces memory overhead * on large data sets by on average (growth factor)/2, mostly * eliminates copies within the vector during resizing, and provides stable * references to its elements. */ template<typename T, size_t ChunkSize> class ChunkedVector { private: uint32_t size_ = 0; std::vector<std::vector<T>> chunks; /** * Keep this out of the ::add hot path */ [[gnu::noinline]] auto & addChunk() { if (size_ >= std::numeric_limits<uint32_t>::max() - ChunkSize) unreachable(); chunks.emplace_back(); chunks.back().reserve(ChunkSize); return chunks.back(); } public: ChunkedVector(uint32_t reserve) { chunks.reserve(reserve); addChunk(); } uint32_t size() const { return size_; } std::pair<T &, uint32_t> add(T value) { const auto idx = size_++; auto & chunk = [&] () -> auto & { if (auto & back = chunks.back(); back.size() < ChunkSize) return back; return addChunk(); }(); auto & result = chunk.emplace_back(std::move(value)); return {result, idx}; } const T & operator[](uint32_t idx) const { return chunks[idx / ChunkSize][idx % ChunkSize]; } template<typename Fn> void forEach(Fn fn) const { for (const auto & c : chunks) for (const auto & e : c) fn(e); } }; }
1,862
C++
.h
65
23.092308
75
0.615557
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,199
util.hh
NixOS_nix/src/libutil/util.hh
#pragma once ///@file #include "types.hh" #include "error.hh" #include "logging.hh" #include <functional> #include <map> #include <sstream> #include <optional> #include "strings.hh" namespace nix { void initLibUtil(); /** * Convert a list of strings to a null-terminated vector of `char * *`s. The result must not be accessed beyond the lifetime of the * list of strings. */ std::vector<char *> stringsToCharPtrs(const Strings & ss); MakeError(FormatError, Error); template<class... Parts> auto concatStrings(Parts &&... parts) -> std::enable_if_t<(... && std::is_convertible_v<Parts, std::string_view>), std::string> { std::string_view views[sizeof...(parts)] = {parts...}; return concatStringsSep({}, views); } /** * Add quotes around a collection of strings. */ template<class C> Strings quoteStrings(const C & c) { Strings res; for (auto & s : c) res.push_back("'" + s + "'"); return res; } /** * Remove trailing whitespace from a string. * * \todo return std::string_view. */ std::string chomp(std::string_view s); /** * Remove whitespace from the start and end of a string. */ std::string trim(std::string_view s, std::string_view whitespace = " \n\r\t"); /** * Replace all occurrences of a string inside another string. */ std::string replaceStrings( std::string s, std::string_view from, std::string_view to); std::string rewriteStrings(std::string s, const StringMap & rewrites); /** * Parse a string into an integer. */ template<class N> std::optional<N> string2Int(const std::string_view s); /** * Like string2Int(), but support an optional suffix 'K', 'M', 'G' or * 'T' denoting a binary unit prefix. */ template<class N> N string2IntWithUnitPrefix(std::string_view s) { uint64_t multiplier = 1; if (!s.empty()) { char u = std::toupper(*s.rbegin()); if (std::isalpha(u)) { if (u == 'K') multiplier = 1ULL << 10; else if (u == 'M') multiplier = 1ULL << 20; else if (u == 'G') multiplier = 1ULL << 30; else if (u == 'T') multiplier = 1ULL << 40; else throw UsageError("invalid unit specifier '%1%'", u); s.remove_suffix(1); } } if (auto n = string2Int<N>(s)) return *n * multiplier; throw UsageError("'%s' is not an integer", s); } /** * Pretty-print a byte value, e.g. 12433615056 is rendered as `11.6 * GiB`. If `align` is set, the number will be right-justified by * padding with spaces on the left. */ std::string renderSize(uint64_t value, bool align = false); /** * Parse a string into a float. */ template<class N> std::optional<N> string2Float(const std::string_view s); /** * Convert a little-endian integer to host order. */ template<typename T> T readLittleEndian(unsigned char * p) { T x = 0; for (size_t i = 0; i < sizeof(x); ++i, ++p) { x |= ((T) *p) << (i * 8); } return x; } /** * @return true iff `s` starts with `prefix`. */ bool hasPrefix(std::string_view s, std::string_view prefix); /** * @return true iff `s` ends in `suffix`. */ bool hasSuffix(std::string_view s, std::string_view suffix); /** * Convert a string to lower case. */ std::string toLower(std::string s); /** * Escape a string as a shell word. */ std::string shellEscape(const std::string_view s); /** * Exception handling in destructors: print an error message, then * ignore the exception. * * If you're not in a destructor, you usually want to use `ignoreExceptionExceptInterrupt()`. * * This function might also be used in callbacks whose caller may not handle exceptions, * but ideally we propagate the exception using an exception_ptr in such cases. * See e.g. `PackBuilderContext` */ void ignoreExceptionInDestructor(Verbosity lvl = lvlError); /** * Not destructor-safe. * Print an error message, then ignore the exception. * If the exception is an `Interrupted` exception, rethrow it. * * This may be used in a few places where Interrupt can't happen, but that's ok. */ void ignoreExceptionExceptInterrupt(Verbosity lvl = lvlError); /** * Tree formatting. */ constexpr char treeConn[] = "├───"; constexpr char treeLast[] = "└───"; constexpr char treeLine[] = "│ "; constexpr char treeNull[] = " "; /** * Encode arbitrary bytes as Base64. */ std::string base64Encode(std::string_view s); /** * Decode arbitrary bytes to Base64. */ std::string base64Decode(std::string_view s); /** * Remove common leading whitespace from the lines in the string * 's'. For example, if every line is indented by at least 3 spaces, * then we remove 3 spaces from the start of every line. */ std::string stripIndentation(std::string_view s); /** * Get the prefix of 's' up to and excluding the next line break (LF * optionally preceded by CR), and the remainder following the line * break. */ std::pair<std::string_view, std::string_view> getLine(std::string_view s); /** * Get a value for the specified key from an associate container. */ template <class T> const typename T::mapped_type * get(const T & map, const typename T::key_type & key) { auto i = map.find(key); if (i == map.end()) return nullptr; return &i->second; } template <class T> typename T::mapped_type * get(T & map, const typename T::key_type & key) { auto i = map.find(key); if (i == map.end()) return nullptr; return &i->second; } /** * Get a value for the specified key from an associate container, or a default value if the key isn't present. */ template <class T> const typename T::mapped_type & getOr(T & map, const typename T::key_type & key, const typename T::mapped_type & defaultValue) { auto i = map.find(key); if (i == map.end()) return defaultValue; return i->second; } /** * Remove and return the first item from a container. */ template <class T> std::optional<typename T::value_type> remove_begin(T & c) { auto i = c.begin(); if (i == c.end()) return {}; auto v = std::move(*i); c.erase(i); return v; } /** * Remove and return the first item from a container. */ template <class T> std::optional<typename T::value_type> pop(T & c) { if (c.empty()) return {}; auto v = std::move(c.front()); c.pop(); return v; } template<typename T> class Callback; /** * A RAII helper that increments a counter on construction and * decrements it on destruction. */ template<typename T> struct MaintainCount { T & counter; long delta; MaintainCount(T & counter, long delta = 1) : counter(counter), delta(delta) { counter += delta; } ~MaintainCount() { counter -= delta; } }; /** * A Rust/Python-like enumerate() iterator adapter. * * Borrowed from http://reedbeta.com/blog/python-like-enumerate-in-cpp17. */ template <typename T, typename TIter = decltype(std::begin(std::declval<T>())), typename = decltype(std::end(std::declval<T>()))> constexpr auto enumerate(T && iterable) { struct iterator { size_t i; TIter iter; constexpr bool operator != (const iterator & other) const { return iter != other.iter; } constexpr void operator ++ () { ++i; ++iter; } constexpr auto operator * () const { return std::tie(i, *iter); } }; struct iterable_wrapper { T iterable; constexpr auto begin() { return iterator{ 0, std::begin(iterable) }; } constexpr auto end() { return iterator{ 0, std::end(iterable) }; } }; return iterable_wrapper{ std::forward<T>(iterable) }; } /** * C++17 std::visit boilerplate */ template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; std::string showBytes(uint64_t bytes); /** * Provide an addition operator between strings and string_views * inexplicably omitted from the standard library. */ inline std::string operator + (const std::string & s1, std::string_view s2) { auto s = s1; s.append(s2); return s; } inline std::string operator + (std::string && s, std::string_view s2) { s.append(s2); return std::move(s); } inline std::string operator + (std::string_view s1, const char * s2) { std::string s; s.reserve(s1.size() + strlen(s2)); s.append(s1); s.append(s2); return s; } }
8,356
C++
.h
289
25.788927
110
0.664786
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,200
strings.hh
NixOS_nix/src/libutil/strings.hh
#pragma once #include <list> #include <set> #include <string_view> #include <string> #include <vector> namespace nix { /* * workaround for unavailable view() method (C++20) of std::ostringstream under MacOS with clang-16 */ std::string_view toView(const std::ostringstream & os); /** * String tokenizer. * * See also `basicSplitString()`, which preserves empty strings between separators, as well as at the start and end. */ template<class C, class CharT = char> C basicTokenizeString(std::basic_string_view<CharT> s, std::basic_string_view<CharT> separators); /** * Like `basicTokenizeString` but specialized to the default `char` */ template<class C> C tokenizeString(std::string_view s, std::string_view separators = " \t\n\r"); extern template std::list<std::string> tokenizeString(std::string_view s, std::string_view separators); extern template std::set<std::string> tokenizeString(std::string_view s, std::string_view separators); extern template std::vector<std::string> tokenizeString(std::string_view s, std::string_view separators); /** * Split a string, preserving empty strings between separators, as well as at the start and end. * * Returns a non-empty collection of strings. */ template<class C, class CharT = char> C basicSplitString(std::basic_string_view<CharT> s, std::basic_string_view<CharT> separators); template<typename C> C splitString(std::string_view s, std::string_view separators); extern template std::list<std::string> splitString(std::string_view s, std::string_view separators); extern template std::set<std::string> splitString(std::string_view s, std::string_view separators); extern template std::vector<std::string> splitString(std::string_view s, std::string_view separators); /** * Concatenate the given strings with a separator between the elements. */ template<class C> std::string concatStringsSep(const std::string_view sep, const C & ss); extern template std::string concatStringsSep(std::string_view, const std::list<std::string> &); extern template std::string concatStringsSep(std::string_view, const std::set<std::string> &); extern template std::string concatStringsSep(std::string_view, const std::vector<std::string> &); /** * Ignore any empty strings at the start of the list, and then concatenate the * given strings with a separator between the elements. * * @deprecated This function exists for historical reasons. You probably just * want to use `concatStringsSep`. */ template<class C> [[deprecated( "Consider removing the empty string dropping behavior. If acceptable, use concatStringsSep instead.")]] std::string dropEmptyInitThenConcatStringsSep(const std::string_view sep, const C & ss); extern template std::string dropEmptyInitThenConcatStringsSep(std::string_view, const std::list<std::string> &); extern template std::string dropEmptyInitThenConcatStringsSep(std::string_view, const std::set<std::string> &); extern template std::string dropEmptyInitThenConcatStringsSep(std::string_view, const std::vector<std::string> &); }
3,043
C++
.h
61
48.278689
119
0.768609
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,201
signals.hh
NixOS_nix/src/libutil/signals.hh
#pragma once ///@file #include "types.hh" #include "error.hh" #include "logging.hh" #include <functional> namespace nix { /* User interruption. */ /** * @note Does nothing on Windows */ static inline void setInterrupted(bool isInterrupted); /** * @note Does nothing on Windows */ static inline bool getInterrupted(); /** * @note Does nothing on Windows */ void setInterruptThrown(); /** * @note Does nothing on Windows */ inline void checkInterrupt(); /** * @note Never will happen on Windows */ MakeError(Interrupted, BaseError); struct InterruptCallback { virtual ~InterruptCallback() { }; }; /** * Register a function that gets called on SIGINT (in a non-signal * context). * * @note Does nothing on Windows */ std::unique_ptr<InterruptCallback> createInterruptCallback( std::function<void()> callback); /** * A RAII class that causes the current thread to receive SIGUSR1 when * the signal handler thread receives SIGINT. That is, this allows * SIGINT to be multiplexed to multiple threads. * * @note Does nothing on Windows */ struct ReceiveInterrupts; } #include "signals-impl.hh"
1,131
C++
.h
50
20.74
70
0.746717
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,202
os-string.hh
NixOS_nix/src/libutil/os-string.hh
#pragma once ///@file #include <optional> #include <string> #include <string_view> namespace nix { /** * Named because it is similar to the Rust type, except it is in the * native encoding not WTF-8. * * Same as `std::filesystem::path::value_type`, but manually defined to * avoid including a much more complex header. */ using OsChar = #if defined(_WIN32) && !defined(__CYGWIN__) wchar_t #else char #endif ; /** * Named because it is similar to the Rust type, except it is in the * native encoding not WTF-8. * * Same as `std::filesystem::path::string_type`, but manually defined * for the same reason as `OsChar`. */ using OsString = std::basic_string<OsChar>; /** * `std::string_view` counterpart for `OsString`. */ using OsStringView = std::basic_string_view<OsChar>; std::string os_string_to_string(OsStringView path); OsString string_to_os_string(std::string_view s); /** * Create string literals with the native character width of paths */ #ifndef _WIN32 # define OS_STR(s) s #else # define OS_STR(s) L##s #endif }
1,061
C++
.h
43
22.813953
71
0.717542
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,203
pool.hh
NixOS_nix/src/libutil/pool.hh
#pragma once ///@file #include <functional> #include <limits> #include <list> #include <memory> #include <cassert> #include "sync.hh" #include "ref.hh" namespace nix { /** * This template class implements a simple pool manager of resources * of some type R, such as database connections. It is used as * follows: * * class Connection { ... }; * * Pool<Connection> pool; * * { * auto conn(pool.get()); * conn->exec("select ..."); * } * * Here, the Connection object referenced by ‘conn’ is automatically * returned to the pool when ‘conn’ goes out of scope. */ template <class R> class Pool { public: /** * A function that produces new instances of R on demand. */ typedef std::function<ref<R>()> Factory; /** * A function that checks whether an instance of R is still * usable. Unusable instances are removed from the pool. */ typedef std::function<bool(const ref<R> &)> Validator; private: Factory factory; Validator validator; struct State { size_t inUse = 0; size_t max; std::vector<ref<R>> idle; }; Sync<State> state; std::condition_variable wakeup; public: Pool(size_t max = std::numeric_limits<size_t>::max(), const Factory & factory = []() { return make_ref<R>(); }, const Validator & validator = [](ref<R> r) { return true; }) : factory(factory) , validator(validator) { auto state_(state.lock()); state_->max = max; } void incCapacity() { auto state_(state.lock()); state_->max++; /* we could wakeup here, but this is only used when we're * about to nest Pool usages, and we want to save the slot for * the nested use if we can */ } void decCapacity() { auto state_(state.lock()); state_->max--; } ~Pool() { auto state_(state.lock()); assert(!state_->inUse); state_->max = 0; state_->idle.clear(); } class Handle { private: Pool & pool; std::shared_ptr<R> r; bool bad = false; friend Pool; Handle(Pool & pool, std::shared_ptr<R> r) : pool(pool), r(r) { } public: // NOTE: Copying std::shared_ptr and calling a .reset() on it is always noexcept. Handle(Handle && h) noexcept : pool(h.pool) , r(h.r) { static_assert(noexcept(h.r.reset())); static_assert(noexcept(std::shared_ptr(h.r))); h.r.reset(); } Handle(const Handle & l) = delete; ~Handle() { if (!r) return; { auto state_(pool.state.lock()); if (!bad) state_->idle.push_back(ref<R>(r)); assert(state_->inUse); state_->inUse--; } pool.wakeup.notify_one(); } R * operator -> () { return &*r; } R & operator * () { return *r; } void markBad() { bad = true; } }; Handle get() { { auto state_(state.lock()); /* If we're over the maximum number of instance, we need to wait until a slot becomes available. */ while (state_->idle.empty() && state_->inUse >= state_->max) state_.wait(wakeup); while (!state_->idle.empty()) { auto p = state_->idle.back(); state_->idle.pop_back(); if (validator(p)) { state_->inUse++; return Handle(*this, p); } } state_->inUse++; } /* We need to create a new instance. Because that might take a while, we don't hold the lock in the meantime. */ try { Handle h(*this, factory()); return h; } catch (...) { auto state_(state.lock()); state_->inUse--; wakeup.notify_one(); throw; } } size_t count() { auto state_(state.lock()); return state_->idle.size() + state_->inUse; } size_t capacity() { return state.lock()->max; } void flushBad() { auto state_(state.lock()); std::vector<ref<R>> left; for (auto & p : state_->idle) if (validator(p)) left.push_back(p); std::swap(state_->idle, left); } }; }
4,555
C++
.h
167
19.359281
89
0.512767
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,204
repair-flag.hh
NixOS_nix/src/libutil/repair-flag.hh
#pragma once ///@file namespace nix { enum RepairFlag : bool { NoRepair = false, Repair = true }; }
103
C++
.h
5
19
59
0.705263
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,205
regex-combinators.hh
NixOS_nix/src/libutil/regex-combinators.hh
#pragma once ///@file #include <string_view> namespace nix::regex { // TODO use constexpr string building like // https://github.com/akrzemi1/static_string/blob/master/include/ak_toolkit/static_string.hpp static inline std::string either(std::string_view a, std::string_view b) { return std::string { a } + "|" + b; } static inline std::string group(std::string_view a) { return std::string { "(" } + a + ")"; } static inline std::string many(std::string_view a) { return std::string { "(?:" } + a + ")*"; } static inline std::string list(std::string_view a) { return std::string { a } + many(group("," + a)); } }
638
C++
.h
23
25.695652
93
0.667216
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,206
file-path-impl.hh
NixOS_nix/src/libutil/file-path-impl.hh
#pragma once /** * @file * * Pure (no IO) infrastructure just for defining other path types; * should not be used directly outside of utilities. */ #include <string> #include <string_view> namespace nix { /** * Unix-style path primives. * * Nix'result own "logical" paths are always Unix-style. So this is always * used for that, and additionally used for native paths on Unix. */ struct UnixPathTrait { using CharT = char; using String = std::string; using StringView = std::string_view; constexpr static char preferredSep = '/'; static inline bool isPathSep(char c) { return c == '/'; } static inline size_t findPathSep(StringView path, size_t from = 0) { return path.find('/', from); } static inline size_t rfindPathSep(StringView path, size_t from = StringView::npos) { return path.rfind('/', from); } }; /** * Windows-style path primitives. * * The character type is a parameter because while windows paths rightly * work over UTF-16 (*) using `wchar_t`, at the current time we are * often manipulating them converted to UTF-8 (*) using `char`. * * (Actually neither are guaranteed to be valid unicode; both are * arbitrary non-0 8- or 16-bit bytes. But for charcters with specifical * meaning like '/', '\\', ':', etc., we refer to an encoding scheme, * and also for sake of UIs that display paths a text.) */ template<class CharT0> struct WindowsPathTrait { using CharT = CharT0; using String = std::basic_string<CharT>; using StringView = std::basic_string_view<CharT>; constexpr static CharT preferredSep = '\\'; static inline bool isPathSep(CharT c) { return c == '/' || c == preferredSep; } static size_t findPathSep(StringView path, size_t from = 0) { size_t p1 = path.find('/', from); size_t p2 = path.find(preferredSep, from); return p1 == String::npos ? p2 : p2 == String::npos ? p1 : std::min(p1, p2); } static size_t rfindPathSep(StringView path, size_t from = String::npos) { size_t p1 = path.rfind('/', from); size_t p2 = path.rfind(preferredSep, from); return p1 == String::npos ? p2 : p2 == String::npos ? p1 : std::max(p1, p2); } }; template<typename CharT> using OsPathTrait = #ifdef _WIN32 WindowsPathTrait<CharT> #else UnixPathTrait #endif ; /** * Core pure path canonicalization algorithm. * * @param hookComponent * A callback which is passed two arguments, * references to * * 1. the result so far * * 2. the remaining path to resolve * * This is a chance to modify those two paths in arbitrary way, e.g. if * "result" points to a symlink. */ template<class PathDict> typename PathDict::String canonPathInner( typename PathDict::StringView remaining, auto && hookComponent) { assert(remaining != ""); typename PathDict::String result; result.reserve(256); while (true) { /* Skip slashes. */ while (!remaining.empty() && PathDict::isPathSep(remaining[0])) remaining.remove_prefix(1); if (remaining.empty()) break; auto nextComp = ({ auto nextPathSep = PathDict::findPathSep(remaining); nextPathSep == remaining.npos ? remaining : remaining.substr(0, nextPathSep); }); /* Ignore `.'. */ if (nextComp == ".") remaining.remove_prefix(1); /* If `..', delete the last component. */ else if (nextComp == "..") { if (!result.empty()) result.erase(PathDict::rfindPathSep(result)); remaining.remove_prefix(2); } /* Normal component; copy it. */ else { result += PathDict::preferredSep; if (const auto slash = PathDict::findPathSep(remaining); slash == result.npos) { result += remaining; remaining = {}; } else { result += remaining.substr(0, slash); remaining = remaining.substr(slash); } hookComponent(result, remaining); } } if (result.empty()) result = typename PathDict::String { PathDict::preferredSep }; return result; } }
4,334
C++
.h
141
24.957447
92
0.620043
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,207
canon-path.hh
NixOS_nix/src/libutil/canon-path.hh
#pragma once ///@file #include <string> #include <optional> #include <cassert> #include <iostream> #include <set> #include <vector> namespace nix { /** * A canonical representation of a path. It ensures the following: * * - It always starts with a slash. * * - It never ends with a slash, except if the path is "/". * * - A slash is never followed by a slash (i.e. no empty components). * * - There are no components equal to '.' or '..'. * * `CanonPath` are "virtual" Nix paths for abstract file system objects; * they are always Unix-style paths, regardless of what OS Nix is * running on. The `/` root doesn't denote the ambient host file system * root, but some virtual FS root. * * @note It might be useful to compare `openat(some_fd, "foo/bar")` on * Unix. `"foo/bar"` is a relative path because an absolute path would * "override" the `some_fd` directory file descriptor and escape to the * "system root". Conversely, Nix's abstract file operations *never* escape the * designated virtual file system (i.e. `SourceAccessor` or * `ParseSink`), so `CanonPath` does not need an absolute/relative * distinction. * * @note The path does not need to correspond to an actually existing * path, and the path may or may not have unresolved symlinks. */ class CanonPath { std::string path; public: /** * Construct a canon path from a non-canonical path. Any '.', '..' * or empty components are removed. */ CanonPath(std::string_view raw); explicit CanonPath(const char * raw) : CanonPath(std::string_view(raw)) { } struct unchecked_t { }; CanonPath(unchecked_t _, std::string path) : path(std::move(path)) { } /** * Construct a canon path from a vector of elements. */ CanonPath(const std::vector<std::string> & elems); static CanonPath root; /** * If `raw` starts with a slash, return * `CanonPath(raw)`. Otherwise return a `CanonPath` representing * `root + "/" + raw`. */ CanonPath(std::string_view raw, const CanonPath & root); bool isRoot() const { return path.size() <= 1; } explicit operator std::string_view() const { return path; } const std::string & abs() const { return path; } /** * Like abs(), but return an empty string if this path is * '/'. Thus the returned string never ends in a slash. */ const std::string & absOrEmpty() const { const static std::string epsilon; return isRoot() ? epsilon : path; } const char * c_str() const { return path.c_str(); } std::string_view rel() const { return ((std::string_view) path).substr(1); } const char * rel_c_str() const { auto cs = path.c_str(); assert(cs[0]); // for safety if invariant is broken return &cs[1]; } struct Iterator { std::string_view remaining; size_t slash; Iterator(std::string_view remaining) : remaining(remaining) , slash(remaining.find('/')) { } bool operator != (const Iterator & x) const { return remaining.data() != x.remaining.data(); } bool operator == (const Iterator & x) const { return !(*this != x); } const std::string_view operator * () const { return remaining.substr(0, slash); } void operator ++ () { if (slash == remaining.npos) remaining = remaining.substr(remaining.size()); else { remaining = remaining.substr(slash + 1); slash = remaining.find('/'); } } }; Iterator begin() const { return Iterator(rel()); } Iterator end() const { return Iterator(rel().substr(path.size() - 1)); } std::optional<CanonPath> parent() const; /** * Remove the last component. Panics if this path is the root. */ void pop(); std::optional<std::string_view> dirOf() const { if (isRoot()) return std::nullopt; return ((std::string_view) path).substr(0, path.rfind('/')); } std::optional<std::string_view> baseName() const { if (isRoot()) return std::nullopt; return ((std::string_view) path).substr(path.rfind('/') + 1); } bool operator == (const CanonPath & x) const { return path == x.path; } bool operator != (const CanonPath & x) const { return path != x.path; } /** * Compare paths lexicographically except that path separators * are sorted before any other character. That is, in the sorted order * a directory is always followed directly by its children. For * instance, 'foo' < 'foo/bar' < 'foo!'. */ auto operator <=> (const CanonPath & x) const { auto i = path.begin(); auto j = x.path.begin(); for ( ; i != path.end() && j != x.path.end(); ++i, ++j) { auto c_i = *i; if (c_i == '/') c_i = 0; auto c_j = *j; if (c_j == '/') c_j = 0; if (auto cmp = c_i <=> c_j; cmp != 0) return cmp; } return (i != path.end()) <=> (j != x.path.end()); } /** * Return true if `this` is equal to `parent` or a child of * `parent`. */ bool isWithin(const CanonPath & parent) const; CanonPath removePrefix(const CanonPath & prefix) const; /** * Append another path to this one. */ void extend(const CanonPath & x); /** * Concatenate two paths. */ CanonPath operator / (const CanonPath & x) const; /** * Add a path component to this one. It must not contain any slashes. */ void push(std::string_view c); CanonPath operator / (std::string_view c) const; /** * Check whether access to this path is allowed, which is the case * if 1) `this` is within any of the `allowed` paths; or 2) any of * the `allowed` paths are within `this`. (The latter condition * ensures access to the parents of allowed paths.) */ bool isAllowed(const std::set<CanonPath> & allowed) const; /** * Return a representation `x` of `path` relative to `this`, i.e. * `CanonPath(this.makeRelative(x), this) == path`. */ std::string makeRelative(const CanonPath & path) const; friend class std::hash<CanonPath>; }; std::ostream & operator << (std::ostream & stream, const CanonPath & path); } template<> struct std::hash<nix::CanonPath> { std::size_t operator ()(const nix::CanonPath & s) const noexcept { return std::hash<std::string>{}(s.path); } };
6,620
C++
.h
195
28.138462
79
0.605548
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,208
posix-source-accessor.hh
NixOS_nix/src/libutil/posix-source-accessor.hh
#pragma once #include "source-accessor.hh" namespace nix { struct SourcePath; /** * A source accessor that uses the Unix filesystem. */ struct PosixSourceAccessor : virtual SourceAccessor { /** * Optional root path to prefix all operations into the native file * system. This allows prepending funny things like `C:\` that * `CanonPath` intentionally doesn't support. */ const std::filesystem::path root; PosixSourceAccessor(); PosixSourceAccessor(std::filesystem::path && root); /** * The most recent mtime seen by lstat(). This is a hack to * support dumpPathAndGetMtime(). Should remove this eventually. */ time_t mtime = 0; void readFile( const CanonPath & path, Sink & sink, std::function<void(uint64_t)> sizeCallback) override; bool pathExists(const CanonPath & path) override; std::optional<Stat> maybeLstat(const CanonPath & path) override; DirEntries readDirectory(const CanonPath & path) override; std::string readLink(const CanonPath & path) override; std::optional<std::filesystem::path> getPhysicalPath(const CanonPath & path) override; /** * Create a `PosixSourceAccessor` and `CanonPath` corresponding to * some native path. * * The `PosixSourceAccessor` is rooted as far up the tree as * possible, (e.g. on Windows it could scoped to a drive like * `C:\`). This allows more `..` parent accessing to work. * * See * [`std::filesystem::path::root_path`](https://en.cppreference.com/w/cpp/filesystem/path/root_path) * and * [`std::filesystem::path::relative_path`](https://en.cppreference.com/w/cpp/filesystem/path/relative_path). */ static SourcePath createAtRoot(const std::filesystem::path & path); private: /** * Throw an error if `path` or any of its ancestors are symlinks. */ void assertNoSymlinks(CanonPath path); std::optional<struct stat> cachedLstat(const CanonPath & path); std::filesystem::path makeAbsPath(const CanonPath & path); }; }
2,084
C++
.h
54
33.5
113
0.69334
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,209
terminal.hh
NixOS_nix/src/libutil/terminal.hh
#pragma once ///@file #include <limits> #include <string> namespace nix { /** * Determine whether ANSI escape sequences are appropriate for the * present output. */ bool isTTY(); /** * Truncate a string to 'width' printable characters. If 'filterAll' * is true, all ANSI escape sequences are filtered out. Otherwise, * some escape sequences (such as colour setting) are copied but not * included in the character count. Also, tabs are expanded to * spaces. */ std::string filterANSIEscapes(std::string_view s, bool filterAll = false, unsigned int width = std::numeric_limits<unsigned int>::max()); /** * Recalculate the window size, updating a global variable. * * Used in the `SIGWINCH` signal handler on Unix, for example. */ void updateWindowSize(); /** * @return the number of rows and columns of the terminal. * * The value is cached so this is quick. The cached result is computed * by `updateWindowSize()`. */ std::pair<unsigned short, unsigned short> getWindowSize(); }
1,010
C++
.h
34
27.764706
70
0.740206
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,210
error.hh
NixOS_nix/src/libutil/error.hh
#pragma once /** * @file * * @brief This file defines two main structs/classes used in nix error handling. * * ErrorInfo provides a standard payload of error information, with conversion to string * happening in the logger rather than at the call site. * * BaseError is the ancestor of nix specific exceptions (and Interrupted), and contains * an ErrorInfo. * * ErrorInfo structs are sent to the logger as part of an exception, or directly with the * logError or logWarning macros. * See libutil/tests/logging.cc for usage examples. */ #include "suggestions.hh" #include "fmt.hh" #include <cstring> #include <list> #include <memory> #include <optional> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> namespace nix { typedef enum { lvlError = 0, lvlWarn, lvlNotice, lvlInfo, lvlTalkative, lvlChatty, lvlDebug, lvlVomit } Verbosity; /** * The lines of code surrounding an error. */ struct LinesOfCode { std::optional<std::string> prevLineOfCode; std::optional<std::string> errLineOfCode; std::optional<std::string> nextLineOfCode; }; struct Pos; void printCodeLines(std::ostream & out, const std::string & prefix, const Pos & errPos, const LinesOfCode & loc); /** * When a stack frame is printed. */ enum struct TracePrint { /** * The default behavior; always printed when `--show-trace` is set. */ Default, /** Always printed. Produced by `builtins.addErrorContext`. */ Always, }; struct Trace { std::shared_ptr<Pos> pos; HintFmt hint; TracePrint print = TracePrint::Default; }; inline std::strong_ordering operator<=>(const Trace& lhs, const Trace& rhs); struct ErrorInfo { Verbosity level; HintFmt msg; std::shared_ptr<Pos> pos; std::list<Trace> traces; /** * Some messages are generated directly by expressions; notably `builtins.warn`, `abort`, `throw`. * These may be rendered differently, so that users can distinguish them. */ bool isFromExpr = false; /** * Exit status. */ unsigned int status = 1; Suggestions suggestions; static std::optional<std::string> programName; }; std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool showTrace); /** * BaseError should generally not be caught, as it has Interrupted as * a subclass. Catch Error instead. */ class BaseError : public std::exception { protected: mutable ErrorInfo err; /** * Cached formatted contents of `err.msg`. */ mutable std::optional<std::string> what_; /** * Format `err.msg` and set `what_` to the resulting value. */ const std::string & calcWhat() const; public: BaseError(const BaseError &) = default; BaseError& operator=(const BaseError &) = default; BaseError& operator=(BaseError &&) = default; template<typename... Args> BaseError(unsigned int status, const Args & ... args) : err { .level = lvlError, .msg = HintFmt(args...), .status = status } { } template<typename... Args> explicit BaseError(const std::string & fs, const Args & ... args) : err { .level = lvlError, .msg = HintFmt(fs, args...) } { } template<typename... Args> BaseError(const Suggestions & sug, const Args & ... args) : err { .level = lvlError, .msg = HintFmt(args...), .suggestions = sug } { } BaseError(HintFmt hint) : err { .level = lvlError, .msg = hint } { } BaseError(ErrorInfo && e) : err(std::move(e)) { } BaseError(const ErrorInfo & e) : err(e) { } /** The error message without "error: " prefixed to it. */ std::string message() { return err.msg.str(); } const char * what() const noexcept override { return calcWhat().c_str(); } const std::string & msg() const { return calcWhat(); } const ErrorInfo & info() const { calcWhat(); return err; } void withExitStatus(unsigned int status) { err.status = status; } void atPos(std::shared_ptr<Pos> pos) { err.pos = pos; } void pushTrace(Trace trace) { err.traces.push_front(trace); } template<typename... Args> void addTrace(std::shared_ptr<Pos> && e, std::string_view fs, const Args & ... args) { addTrace(std::move(e), HintFmt(std::string(fs), args...)); } void addTrace(std::shared_ptr<Pos> && e, HintFmt hint, TracePrint print = TracePrint::Default); bool hasTrace() const { return !err.traces.empty(); } const ErrorInfo & info() { return err; }; }; #define MakeError(newClass, superClass) \ class newClass : public superClass \ { \ public: \ using superClass::superClass; \ } MakeError(Error, BaseError); MakeError(UsageError, Error); MakeError(UnimplementedError, Error); /** * To use in catch-blocks. */ MakeError(SystemError, Error); /** * POSIX system error, created using `errno`, `strerror` friends. * * Throw this, but prefer not to catch this, and catch `SystemError` * instead. This allows implementations to freely switch between this * and `windows::WinError` without breaking catch blocks. * * However, it is permissible to catch this and rethrow so long as * certain conditions are not met (e.g. to catch only if `errNo = * EFooBar`). In that case, try to also catch the equivalent `windows::WinError` * code. * * @todo Rename this to `PosixError` or similar. At this point Windows * support is too WIP to justify the code churn, but if it is finished * then a better identifier becomes moe worth it. */ class SysError : public SystemError { public: int errNo; /** * Construct using the explicitly-provided error number. `strerror` * will be used to try to add additional information to the message. */ template<typename... Args> SysError(int errNo, const Args & ... args) : SystemError(""), errNo(errNo) { auto hf = HintFmt(args...); err.msg = HintFmt("%1%: %2%", Uncolored(hf.str()), strerror(errNo)); } /** * Construct using the ambient `errno`. * * Be sure to not perform another `errno`-modifying operation before * calling this constructor! */ template<typename... Args> SysError(const Args & ... args) : SysError(errno, args ...) { } }; #ifdef _WIN32 namespace windows { class WinError; } #endif /** * Convenience alias for when we use a `errno`-based error handling * function on Unix, and `GetLastError()`-based error handling on on * Windows. */ using NativeSysError = #ifdef _WIN32 windows::WinError #else SysError #endif ; /** * Throw an exception for the purpose of checking that exception * handling works; see 'initLibUtil()'. */ void throwExceptionSelfCheck(); /** * Print a message and abort(). */ [[noreturn]] void panic(std::string_view msg); /** * Print a basic error message with source position and abort(). * Use the unreachable() macro to call this. */ [[noreturn]] void panic(const char * file, int line, const char * func); /** * Print a basic error message with source position and abort(). * * @note: This assumes that the logger is operational */ #define unreachable() (::nix::panic(__FILE__, __LINE__, __func__)) }
7,439
C++
.h
248
26.169355
102
0.658267
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,211
environment-variables.hh
NixOS_nix/src/libutil/environment-variables.hh
#pragma once /** * @file * * Utilities for working with the current process's environment * variables. */ #include <optional> #include "types.hh" #include "file-path.hh" namespace nix { static constexpr auto environmentVariablesCategory = "Options that change environment variables"; /** * @return an environment variable. */ std::optional<std::string> getEnv(const std::string & key); /** * Like `getEnv`, but using `OsString` to avoid coercions. */ std::optional<OsString> getEnvOs(const OsString & key); /** * @return a non empty environment variable. Returns nullopt if the env * variable is set to "" */ std::optional<std::string> getEnvNonEmpty(const std::string & key); /** * Get the entire environment. */ std::map<std::string, std::string> getEnv(); #ifdef _WIN32 /** * Implementation of missing POSIX function. */ int unsetenv(const char * name); #endif /** * Like POSIX `setenv`, but always overrides. * * We don't need the non-overriding version, and this is easier to * reimplement on Windows. */ int setEnv(const char * name, const char * value); /** * Like `setEnv`, but using `OsString` to avoid coercions. */ int setEnvOs(const OsString & name, const OsString & value); /** * Clear the environment. */ void clearEnv(); /** * Replace the entire environment with the given one. */ void replaceEnv(const std::map<std::string, std::string> & newEnv); }
1,407
C++
.h
55
23.836364
97
0.72571
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,212
finally.hh
NixOS_nix/src/libutil/finally.hh
#pragma once ///@file #include <utility> #include <cassert> #include <exception> /** * A trivial class to run a function at the end of a scope. */ template<typename Fn> class [[nodiscard("Finally values must be used")]] Finally { private: Fn fun; bool movedFrom = false; public: Finally(Fn fun) : fun(std::move(fun)) { } // Copying Finallys is definitely not a good idea and will cause them to be // called twice. Finally(Finally &other) = delete; // NOTE: Move constructor can be nothrow if the callable type is itself nothrow // move-constructible. Finally(Finally && other) noexcept(std::is_nothrow_move_constructible_v<Fn>) : fun(std::move(other.fun)) { other.movedFrom = true; } ~Finally() noexcept(false) { try { if (!movedFrom) fun(); } catch (...) { // finally may only throw an exception if exception handling is not already // in progress. if handling *is* in progress we have to return cleanly here // but are still prohibited from doing so since eating the exception would, // in almost all cases, mess up error handling even more. the only good way // to handle this is to abort entirely and leave a message, so we'll assert // (and rethrow anyway, just as a defense against possible NASSERT builds.) if (std::uncaught_exceptions()) { assert(false && "Finally function threw an exception during exception handling. " "this is not what you want, please use some other methods (like " "std::promise or async) instead."); } throw; } } };
1,761
C++
.h
48
29.166667
87
0.615205
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,213
hilite.hh
NixOS_nix/src/libutil/hilite.hh
#pragma once ///@file #include <regex> #include <vector> #include <string> namespace nix { /** * Highlight all the given matches in the given string `s` by wrapping * them between `prefix` and `postfix`. * * If some matches overlap, then their union will be wrapped rather * than the individual matches. */ std::string hiliteMatches( std::string_view s, std::vector<std::smatch> matches, std::string_view prefix, std::string_view postfix); }
468
C++
.h
19
22.263158
70
0.723596
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,214
logging.hh
NixOS_nix/src/libutil/logging.hh
#pragma once ///@file #include "error.hh" #include "config.hh" #include <nlohmann/json_fwd.hpp> namespace nix { typedef enum { actUnknown = 0, actCopyPath = 100, actFileTransfer = 101, actRealise = 102, actCopyPaths = 103, actBuilds = 104, actBuild = 105, actOptimiseStore = 106, actVerifyPaths = 107, actSubstitute = 108, actQueryPathInfo = 109, actPostBuildHook = 110, actBuildWaiting = 111, actFetchTree = 112, } ActivityType; typedef enum { resFileLinked = 100, resBuildLogLine = 101, resUntrustedPath = 102, resCorruptedPath = 103, resSetPhase = 104, resProgress = 105, resSetExpected = 106, resPostBuildLogLine = 107, resFetchStatus = 108, } ResultType; typedef uint64_t ActivityId; struct LoggerSettings : Config { Setting<bool> showTrace{ this, false, "show-trace", R"( Whether Nix should print out a stack trace in case of Nix expression evaluation errors. )"}; }; extern LoggerSettings loggerSettings; class Logger { friend struct Activity; public: struct Field { // FIXME: use std::variant. enum { tInt = 0, tString = 1 } type; uint64_t i = 0; std::string s; Field(const std::string & s) : type(tString), s(s) { } Field(const char * s) : type(tString), s(s) { } Field(const uint64_t & i) : type(tInt), i(i) { } }; typedef std::vector<Field> Fields; virtual ~Logger() { } virtual void stop() { }; virtual void pause() { }; virtual void resume() { }; // Whether the logger prints the whole build log virtual bool isVerbose() { return false; } virtual void log(Verbosity lvl, std::string_view s) = 0; void log(std::string_view s) { log(lvlInfo, s); } virtual void logEI(const ErrorInfo & ei) = 0; void logEI(Verbosity lvl, ErrorInfo ei) { ei.level = lvl; logEI(ei); } virtual void warn(const std::string & msg); virtual void startActivity(ActivityId act, Verbosity lvl, ActivityType type, const std::string & s, const Fields & fields, ActivityId parent) { }; virtual void stopActivity(ActivityId act) { }; virtual void result(ActivityId act, ResultType type, const Fields & fields) { }; virtual void writeToStdout(std::string_view s); template<typename... Args> inline void cout(const Args & ... args) { writeToStdout(fmt(args...)); } virtual std::optional<char> ask(std::string_view s) { return {}; } virtual void setPrintBuildLogs(bool printBuildLogs) { } }; /** * A variadic template that does nothing. * * Useful to call a function with each argument in a parameter pack. */ struct nop { template<typename... T> nop(T...) { } }; ActivityId getCurActivity(); void setCurActivity(const ActivityId activityId); struct Activity { Logger & logger; const ActivityId id; Activity(Logger & logger, Verbosity lvl, ActivityType type, const std::string & s = "", const Logger::Fields & fields = {}, ActivityId parent = getCurActivity()); Activity(Logger & logger, ActivityType type, const Logger::Fields & fields = {}, ActivityId parent = getCurActivity()) : Activity(logger, lvlError, type, "", fields, parent) { }; Activity(const Activity & act) = delete; ~Activity(); void progress(uint64_t done = 0, uint64_t expected = 0, uint64_t running = 0, uint64_t failed = 0) const { result(resProgress, done, expected, running, failed); } void setExpected(ActivityType type2, uint64_t expected) const { result(resSetExpected, type2, expected); } template<typename... Args> void result(ResultType type, const Args & ... args) const { Logger::Fields fields; nop{(fields.emplace_back(Logger::Field(args)), 1)...}; result(type, fields); } void result(ResultType type, const Logger::Fields & fields) const { logger.result(id, type, fields); } friend class Logger; }; struct PushActivity { const ActivityId prevAct; PushActivity(ActivityId act) : prevAct(getCurActivity()) { setCurActivity(act); } ~PushActivity() { setCurActivity(prevAct); } }; extern Logger * logger; Logger * makeSimpleLogger(bool printBuildLogs = true); Logger * makeJSONLogger(Logger & prevLogger); std::optional<nlohmann::json> parseJSONMessage(const std::string & msg); bool handleJSONLogMessage(nlohmann::json & json, const Activity & act, std::map<ActivityId, Activity> & activities, bool trusted); bool handleJSONLogMessage(const std::string & msg, const Activity & act, std::map<ActivityId, Activity> & activities, bool trusted); /** * suppress msgs > this */ extern Verbosity verbosity; /** * Print a message with the standard ErrorInfo format. * In general, use these 'log' macros for reporting problems that may require user * intervention or that need more explanation. Use the 'print' macros for more * lightweight status messages. */ #define logErrorInfo(level, errorInfo...) \ do { \ if ((level) <= nix::verbosity) { \ logger->logEI((level), errorInfo); \ } \ } while (0) #define logError(errorInfo...) logErrorInfo(lvlError, errorInfo) #define logWarning(errorInfo...) logErrorInfo(lvlWarn, errorInfo) /** * Print a string message if the current log level is at least the specified * level. Note that this has to be implemented as a macro to ensure that the * arguments are evaluated lazily. */ #define printMsgUsing(loggerParam, level, args...) \ do { \ auto __lvl = level; \ if (__lvl <= nix::verbosity) { \ loggerParam->log(__lvl, fmt(args)); \ } \ } while (0) #define printMsg(level, args...) printMsgUsing(logger, level, args) #define printError(args...) printMsg(lvlError, args) #define notice(args...) printMsg(lvlNotice, args) #define printInfo(args...) printMsg(lvlInfo, args) #define printTalkative(args...) printMsg(lvlTalkative, args) #define debug(args...) printMsg(lvlDebug, args) #define vomit(args...) printMsg(lvlVomit, args) /** * if verbosity >= lvlWarn, print a message with a yellow 'warning:' prefix. */ template<typename... Args> inline void warn(const std::string & fs, const Args & ... args) { boost::format f(fs); formatHelper(f, args...); logger->warn(f.str()); } #define warnOnce(haveWarned, args...) \ if (!haveWarned) { \ haveWarned = true; \ warn(args); \ } void writeToStderr(std::string_view s); }
6,675
C++
.h
202
28.490099
108
0.665368
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,215
json-utils.hh
NixOS_nix/src/libutil/json-utils.hh
#pragma once ///@file #include <nlohmann/json.hpp> #include <list> #include "types.hh" namespace nix { enum struct ExperimentalFeature; const nlohmann::json * get(const nlohmann::json & map, const std::string & key); nlohmann::json * get(nlohmann::json & map, const std::string & key); /** * Get the value of a json object at a key safely, failing with a nice * error if the key does not exist. * * Use instead of nlohmann::json::at() to avoid ugly exceptions. */ const nlohmann::json & valueAt( const nlohmann::json::object_t & map, const std::string & key); std::optional<nlohmann::json> optionalValueAt(const nlohmann::json::object_t & value, const std::string & key); /** * Downcast the json object, failing with a nice error if the conversion fails. * See https://json.nlohmann.me/features/types/ */ const nlohmann::json * getNullable(const nlohmann::json & value); const nlohmann::json::object_t & getObject(const nlohmann::json & value); const nlohmann::json::array_t & getArray(const nlohmann::json & value); const nlohmann::json::string_t & getString(const nlohmann::json & value); const nlohmann::json::number_integer_t & getInteger(const nlohmann::json & value); const nlohmann::json::boolean_t & getBoolean(const nlohmann::json & value); Strings getStringList(const nlohmann::json & value); StringMap getStringMap(const nlohmann::json & value); StringSet getStringSet(const nlohmann::json & value); /** * For `adl_serializer<std::optional<T>>` below, we need to track what * types are not already using `null`. Only for them can we use `null` * to represent `std::nullopt`. */ template<typename T> struct json_avoids_null; /** * Handle numbers in default impl */ template<typename T> struct json_avoids_null : std::bool_constant<std::is_integral<T>::value> {}; template<> struct json_avoids_null<std::nullptr_t> : std::false_type {}; template<> struct json_avoids_null<bool> : std::true_type {}; template<> struct json_avoids_null<std::string> : std::true_type {}; template<typename T> struct json_avoids_null<std::vector<T>> : std::true_type {}; template<typename T> struct json_avoids_null<std::list<T>> : std::true_type {}; template<typename K, typename V> struct json_avoids_null<std::map<K, V>> : std::true_type {}; /** * `ExperimentalFeature` is always rendered as a string. */ template<> struct json_avoids_null<ExperimentalFeature> : std::true_type {}; } namespace nlohmann { /** * This "instance" is widely requested, see * https://github.com/nlohmann/json/issues/1749, but momentum has stalled * out. Writing there here in Nix as a stop-gap. * * We need to make sure the underlying type does not use `null` for this to * round trip. We do that with a static assert. */ template<typename T> struct adl_serializer<std::optional<T>> { /** * @brief Convert a JSON type to an `optional<T>` treating * `null` as `std::nullopt`. */ static void from_json(const json & json, std::optional<T> & t) { static_assert( nix::json_avoids_null<T>::value, "null is already in use for underlying type's JSON"); t = json.is_null() ? std::nullopt : std::make_optional(json.template get<T>()); } /** * @brief Convert an optional type to a JSON type treating `std::nullopt` * as `null`. */ static void to_json(json & json, const std::optional<T> & t) { static_assert( nix::json_avoids_null<T>::value, "null is already in use for underlying type's JSON"); if (t) json = *t; else json = nullptr; } }; }
3,669
C++
.h
103
32.174757
111
0.68473
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,217
english.hh
NixOS_nix/src/libutil/english.hh
#pragma once #include <iostream> namespace nix { /** * Pluralize a given value. * * If `count == 1`, prints `1 {single}` to `output`, otherwise prints `{count} {plural}`. */ std::ostream & pluralize( std::ostream & output, unsigned int count, const std::string_view single, const std::string_view plural); }
332
C++
.h
14
21
89
0.671975
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,218
abstract-setting-to-json.hh
NixOS_nix/src/libutil/abstract-setting-to-json.hh
#pragma once ///@file #include <nlohmann/json.hpp> #include "config.hh" #include "json-utils.hh" namespace nix { template<typename T> std::map<std::string, nlohmann::json> BaseSetting<T>::toJSONObject() const { auto obj = AbstractSetting::toJSONObject(); obj.emplace("value", value); obj.emplace("defaultValue", defaultValue); obj.emplace("documentDefault", documentDefault); return obj; } }
414
C++
.h
16
23.5
74
0.734848
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,219
source-accessor.hh
NixOS_nix/src/libutil/source-accessor.hh
#pragma once #include <filesystem> #include "canon-path.hh" #include "hash.hh" #include "ref.hh" namespace nix { struct Sink; /** * Note there is a decent chance this type soon goes away because the problem is solved another way. * See the discussion in https://github.com/NixOS/nix/pull/9985. */ enum class SymlinkResolution { /** * Resolve symlinks in the ancestors only. * * Only the last component of the result is possibly a symlink. */ Ancestors, /** * Resolve symlinks fully, realpath(3)-style. * * No component of the result will be a symlink. */ Full, }; MakeError(FileNotFound, Error); /** * A read-only filesystem abstraction. This is used by the Nix * evaluator and elsewhere for accessing sources in various * filesystem-like entities (such as the real filesystem, tarballs or * Git repositories). */ struct SourceAccessor : std::enable_shared_from_this<SourceAccessor> { const size_t number; std::string displayPrefix, displaySuffix; SourceAccessor(); virtual ~SourceAccessor() { } /** * Return the contents of a file as a string. * * @note Unlike Unix, this method should *not* follow symlinks. Nix * by default wants to manipulate symlinks explicitly, and not * implictly follow them, as they are frequently untrusted user data * and thus may point to arbitrary locations. Acting on the targets * targets of symlinks should only occasionally be done, and only * with care. */ virtual std::string readFile(const CanonPath & path); /** * Write the contents of a file as a sink. `sizeCallback` must be * called with the size of the file before any data is written to * the sink. * * @note Like the other `readFile`, this method should *not* follow * symlinks. * * @note subclasses of `SourceAccessor` need to implement at least * one of the `readFile()` variants. */ virtual void readFile( const CanonPath & path, Sink & sink, std::function<void(uint64_t)> sizeCallback = [](uint64_t size){}); virtual bool pathExists(const CanonPath & path); enum Type { tRegular, tSymlink, tDirectory, /** Any other node types that may be encountered on the file system, such as device nodes, sockets, named pipe, and possibly even more exotic things. Responsible for `"unknown"` from `builtins.readFileType "/dev/null"`. Unlike `DT_UNKNOWN`, this must not be used for deferring the lookup of types. */ tMisc }; struct Stat { Type type = tMisc; /** * For regular files only: the size of the file. Not all * accessors return this since it may be too expensive to * compute. */ std::optional<uint64_t> fileSize; /** * For regular files only: whether this is an executable. */ bool isExecutable = false; /** * For regular files only: the position of the contents of this * file in the NAR. Only returned by NAR accessors. */ std::optional<uint64_t> narOffset; }; Stat lstat(const CanonPath & path); virtual std::optional<Stat> maybeLstat(const CanonPath & path) = 0; typedef std::optional<Type> DirEntry; typedef std::map<std::string, DirEntry> DirEntries; /** * @note Like `readFile`, this method should *not* follow symlinks. */ virtual DirEntries readDirectory(const CanonPath & path) = 0; virtual std::string readLink(const CanonPath & path) = 0; virtual void dumpPath( const CanonPath & path, Sink & sink, PathFilter & filter = defaultPathFilter); Hash hashPath( const CanonPath & path, PathFilter & filter = defaultPathFilter, HashAlgorithm ha = HashAlgorithm::SHA256); /** * Return a corresponding path in the root filesystem, if * possible. This is only possible for filesystems that are * materialized in the root filesystem. */ virtual std::optional<std::filesystem::path> getPhysicalPath(const CanonPath & path) { return std::nullopt; } bool operator == (const SourceAccessor & x) const { return number == x.number; } auto operator <=> (const SourceAccessor & x) const { return number <=> x.number; } void setPathDisplay(std::string displayPrefix, std::string displaySuffix = ""); virtual std::string showPath(const CanonPath & path); /** * Resolve any symlinks in `path` according to the given * resolution mode. * * @param mode might only be a temporary solution for this. * See the discussion in https://github.com/NixOS/nix/pull/9985. */ CanonPath resolveSymlinks( const CanonPath & path, SymlinkResolution mode = SymlinkResolution::Full); /** * A string that uniquely represents the contents of this * accessor. This is used for caching lookups (see `fetchToStore()`). */ std::optional<std::string> fingerprint; /** * Return the maximum last-modified time of the files in this * tree, if available. */ virtual std::optional<time_t> getLastModified() { return std::nullopt; } }; /** * Return a source accessor that contains only an empty root directory. */ ref<SourceAccessor> makeEmptySourceAccessor(); /** * Exception thrown when accessing a filtered path (see * `FilteringSourceAccessor`). */ MakeError(RestrictedPathError, Error); /** * Return an accessor for the root filesystem. */ ref<SourceAccessor> getFSSourceAccessor(); /** * Construct an accessor for the filesystem rooted at `root`. Note * that it is not possible to escape `root` by appending `..` path * elements, and that absolute symlinks are resolved relative to * `root`. */ ref<SourceAccessor> makeFSSourceAccessor(std::filesystem::path root); }
5,986
C++
.h
171
29.561404
153
0.673653
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,220
callback.hh
NixOS_nix/src/libutil/callback.hh
#pragma once ///@file #include <future> #include <functional> namespace nix { /** * A callback is a wrapper around a lambda that accepts a valid of * type T or an exception. (We abuse std::future<T> to pass the value or * exception.) */ template<typename T> class Callback { std::function<void(std::future<T>)> fun; std::atomic_flag done = ATOMIC_FLAG_INIT; public: Callback(std::function<void(std::future<T>)> fun) : fun(fun) { } // NOTE: std::function is noexcept move-constructible since C++20. Callback(Callback && callback) noexcept(std::is_nothrow_move_constructible_v<decltype(fun)>) : fun(std::move(callback.fun)) { auto prev = callback.done.test_and_set(); if (prev) done.test_and_set(); } void operator()(T && t) noexcept { auto prev = done.test_and_set(); assert(!prev); std::promise<T> promise; promise.set_value(std::move(t)); fun(promise.get_future()); } void rethrow(const std::exception_ptr & exc = std::current_exception()) noexcept { auto prev = done.test_and_set(); assert(!prev); std::promise<T> promise; promise.set_exception(exc); fun(promise.get_future()); } }; }
1,256
C++
.h
42
24.880952
96
0.634025
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,221
git.hh
NixOS_nix/src/libutil/git.hh
#pragma once ///@file #include <string> #include <string_view> #include <optional> #include "types.hh" #include "serialise.hh" #include "hash.hh" #include "source-path.hh" #include "fs-sink.hh" namespace nix::git { enum struct ObjectType { Blob, Tree, //Commit, //Tag, }; using RawMode = uint32_t; enum struct Mode : RawMode { Directory = 0040000, Regular = 0100644, Executable = 0100755, Symlink = 0120000, }; std::optional<Mode> decodeMode(RawMode m); /** * An anonymous Git tree object entry (no name part). */ struct TreeEntry { Mode mode; Hash hash; bool operator ==(const TreeEntry &) const = default; auto operator <=>(const TreeEntry &) const = default; }; /** * A Git tree object, fully decoded and stored in memory. * * Directory names must end in a `/` for sake of sorting. See * https://github.com/mirage/irmin/issues/352 */ using Tree = std::map<std::string, TreeEntry>; /** * Callback for processing a child hash with `parse` * * The function should * * 1. Obtain the file system objects denoted by `gitHash` * * 2. Ensure they match `mode` * * 3. Feed them into the same sink `parse` was called with * * Implementations may seek to memoize resources (bandwidth, storage, * etc.) for the same Git hash. */ using SinkHook = void(const CanonPath & name, TreeEntry entry); /** * Parse the "blob " or "tree " prefix. * * @throws if prefix not recognized */ ObjectType parseObjectType( Source & source, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** * These 3 modes are represented by blob objects. * * Sometimes we need this information to disambiguate how a blob is * being used to better match our own "file system object" data model. */ enum struct BlobMode : RawMode { Regular = static_cast<RawMode>(Mode::Regular), Executable = static_cast<RawMode>(Mode::Executable), Symlink = static_cast<RawMode>(Mode::Symlink), }; void parseBlob( FileSystemObjectSink & sink, const CanonPath & sinkPath, Source & source, BlobMode blobMode, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); void parseTree( FileSystemObjectSink & sink, const CanonPath & sinkPath, Source & source, std::function<SinkHook> hook, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** * Helper putting the previous three `parse*` functions together. * * @param rootModeIfBlob How to interpret a root blob, for which there is no * disambiguating dir entry to answer that questino. If the root it not * a blob, this is ignored. */ void parse( FileSystemObjectSink & sink, const CanonPath & sinkPath, Source & source, BlobMode rootModeIfBlob, std::function<SinkHook> hook, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** * Assists with writing a `SinkHook` step (2). */ std::optional<Mode> convertMode(SourceAccessor::Type type); /** * Simplified version of `SinkHook` for `restore`. * * Given a `Hash`, return a `SourceAccessor` and `CanonPath` pointing to * the file system object with that path. */ using RestoreHook = SourcePath(Hash); /** * Wrapper around `parse` and `RestoreSink` */ void restore(FileSystemObjectSink & sink, Source & source, std::function<RestoreHook> hook); /** * Dumps a single file to a sink * * @param xpSettings for testing purposes */ void dumpBlobPrefix( uint64_t size, Sink & sink, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** * Dumps a representation of a git tree to a sink */ void dumpTree( const Tree & entries, Sink & sink, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** * Callback for processing a child with `dump` * * The function should return the Git hash and mode of the file at the * given path in the accessor passed to `dump`. * * Note that if the child is a directory, its child in must also be so * processed in order to compute this information. */ using DumpHook = TreeEntry(const SourcePath & path); Mode dump( const SourcePath & path, Sink & sink, std::function<DumpHook> hook, PathFilter & filter = defaultPathFilter, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** * Recursively dumps path, hashing as we go. * * A smaller wrapper around `dump`. */ TreeEntry dumpHash( HashAlgorithm ha, const SourcePath & path, PathFilter & filter = defaultPathFilter); /** * A line from the output of `git ls-remote --symref`. * * These can be of two kinds: * * - Symbolic references of the form * * ``` * ref: {target} {reference} * ``` * where {target} is itself a reference and {reference} is optional * * - Object references of the form * * ``` * {target} {reference} * ``` * where {target} is a commit id and {reference} is mandatory */ struct LsRemoteRefLine { enum struct Kind { Symbolic, Object }; Kind kind; std::string target; std::optional<std::string> reference; }; /** * Parse an `LsRemoteRefLine` */ std::optional<LsRemoteRefLine> parseLsRemoteLine(std::string_view line); }
5,274
C++
.h
187
25.529412
92
0.721542
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,222
hash.hh
NixOS_nix/src/libutil/hash.hh
#pragma once ///@file #include "types.hh" #include "serialise.hh" #include "file-system.hh" namespace nix { MakeError(BadHash, Error); enum struct HashAlgorithm : char { MD5 = 42, SHA1, SHA256, SHA512 }; const int md5HashSize = 16; const int sha1HashSize = 20; const int sha256HashSize = 32; const int sha512HashSize = 64; extern const std::set<std::string> hashAlgorithms; extern const std::string nix32Chars; /** * @brief Enumeration representing the hash formats. */ enum struct HashFormat : int { /// @brief Base 64 encoding. /// @see [IETF RFC 4648, section 4](https://datatracker.ietf.org/doc/html/rfc4648#section-4). Base64, /// @brief Nix-specific base-32 encoding. @see nix32Chars Nix32, /// @brief Lowercase hexadecimal encoding. @see base16Chars Base16, /// @brief "<hash algo>:<Base 64 hash>", format of the SRI integrity attribute. /// @see W3C recommendation [Subresource Intergrity](https://www.w3.org/TR/SRI/). SRI }; extern const std::set<std::string> hashFormats; struct Hash { constexpr static size_t maxHashSize = 64; size_t hashSize = 0; uint8_t hash[maxHashSize] = {}; HashAlgorithm algo; /** * Create a zero-filled hash object. */ explicit Hash(HashAlgorithm algo); /** * Parse the hash from a string representation in the format * "[<type>:]<base16|base32|base64>" or "<type>-<base64>" (a * Subresource Integrity hash expression). If the 'type' argument * is not present, then the hash algorithm must be specified in the * string. */ static Hash parseAny(std::string_view s, std::optional<HashAlgorithm> optAlgo); /** * Parse a hash from a string representation like the above, except the * type prefix is mandatory is there is no separate arguement. */ static Hash parseAnyPrefixed(std::string_view s); /** * Parse a plain hash that musst not have any prefix indicating the type. * The type is passed in to disambiguate. */ static Hash parseNonSRIUnprefixed(std::string_view s, HashAlgorithm algo); static Hash parseSRI(std::string_view original); private: /** * The type must be provided, the string view must not include <type> * prefix. `isSRI` helps disambigate the various base-* encodings. */ Hash(std::string_view s, HashAlgorithm algo, bool isSRI); public: /** * Check whether two hashes are equal. */ bool operator == (const Hash & h2) const noexcept; /** * Compare how two hashes are ordered. */ std::strong_ordering operator <=> (const Hash & h2) const noexcept; /** * Returns the length of a base-16 representation of this hash. */ [[nodiscard]] size_t base16Len() const { return hashSize * 2; } /** * Returns the length of a base-32 representation of this hash. */ [[nodiscard]] size_t base32Len() const { return (hashSize * 8 - 1) / 5 + 1; } /** * Returns the length of a base-64 representation of this hash. */ [[nodiscard]] size_t base64Len() const { return ((4 * hashSize / 3) + 3) & ~3; } /** * Return a string representation of the hash, in base-16, base-32 * or base-64. By default, this is prefixed by the hash algo * (e.g. "sha256:"). */ [[nodiscard]] std::string to_string(HashFormat hashFormat, bool includeAlgo) const; [[nodiscard]] std::string gitRev() const { return to_string(HashFormat::Base16, false); } [[nodiscard]] std::string gitShortRev() const { return std::string(to_string(HashFormat::Base16, false), 0, 7); } static Hash dummy; /** * @return a random hash with hash algorithm `algo` */ static Hash random(HashAlgorithm algo); }; /** * Helper that defaults empty hashes to the 0 hash. */ Hash newHashAllowEmpty(std::string_view hashStr, std::optional<HashAlgorithm> ha); /** * Print a hash in base-16 if it's MD5, or base-32 otherwise. */ std::string printHash16or32(const Hash & hash); /** * Compute the hash of the given string. */ Hash hashString(HashAlgorithm ha, std::string_view s); /** * Compute the hash of the given file, hashing its contents directly. * * (Metadata, such as the executable permission bit, is ignored.) */ Hash hashFile(HashAlgorithm ha, const Path & path); /** * The final hash and the number of bytes digested. * * @todo Convert to proper struct */ typedef std::pair<Hash, uint64_t> HashResult; /** * Compress a hash to the specified number of bytes by cyclically * XORing bytes together. */ Hash compressHash(const Hash & hash, unsigned int newSize); /** * Parse a string representing a hash format. */ HashFormat parseHashFormat(std::string_view hashFormatName); /** * std::optional version of parseHashFormat that doesn't throw error. */ std::optional<HashFormat> parseHashFormatOpt(std::string_view hashFormatName); /** * The reverse of parseHashFormat. */ std::string_view printHashFormat(HashFormat hashFormat); /** * Parse a string representing a hash algorithm. */ HashAlgorithm parseHashAlgo(std::string_view s); /** * Will return nothing on parse error */ std::optional<HashAlgorithm> parseHashAlgoOpt(std::string_view s); /** * And the reverse. */ std::string_view printHashAlgo(HashAlgorithm ha); union Ctx; struct AbstractHashSink : virtual Sink { virtual HashResult finish() = 0; }; class HashSink : public BufferedSink, public AbstractHashSink { private: HashAlgorithm ha; Ctx * ctx; uint64_t bytes; public: HashSink(HashAlgorithm ha); HashSink(const HashSink & h); ~HashSink(); void writeUnbuffered(std::string_view data) override; HashResult finish() override; HashResult currentHash(); }; }
5,833
C++
.h
188
27.191489
97
0.690493
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,223
types.hh
NixOS_nix/src/libutil/types.hh
#pragma once ///@file #include <list> #include <set> #include <string> #include <map> #include <variant> #include <vector> namespace nix { typedef std::list<std::string> Strings; typedef std::set<std::string> StringSet; typedef std::map<std::string, std::string> StringMap; typedef std::map<std::string, std::string> StringPairs; /** * Paths are just strings. */ typedef std::string Path; typedef std::string_view PathView; typedef std::list<Path> Paths; typedef std::set<Path> PathSet; typedef std::vector<std::pair<std::string, std::string>> Headers; /** * Helper class to run code at startup. */ template<typename T> struct OnStartup { OnStartup(T && t) { t(); } }; /** * Wrap bools to prevent string literals (i.e. 'char *') from being * cast to a bool in Attr. */ template<typename T> struct Explicit { T t; bool operator ==(const Explicit<T> & other) const { return t == other.t; } }; /** * This wants to be a little bit like rust's Cow type. * Some parts of the evaluator benefit greatly from being able to reuse * existing allocations for strings, but have to be able to also use * newly allocated storage for values. * * We do not define implicit conversions, even with ref qualifiers, * since those can easily become ambiguous to the reader and can degrade * into copying behaviour we want to avoid. */ class BackedStringView { private: std::variant<std::string, std::string_view> data; /** * Needed to introduce a temporary since operator-> must return * a pointer. Without this we'd need to store the view object * even when we already own a string. */ class Ptr { private: std::string_view view; public: Ptr(std::string_view view): view(view) {} const std::string_view * operator->() const { return &view; } }; public: BackedStringView(std::string && s): data(std::move(s)) {} BackedStringView(std::string_view sv): data(sv) {} template<size_t N> BackedStringView(const char (& lit)[N]): data(std::string_view(lit)) {} BackedStringView(const BackedStringView &) = delete; BackedStringView & operator=(const BackedStringView &) = delete; /** * We only want move operations defined since the sole purpose of * this type is to avoid copies. */ BackedStringView(BackedStringView && other) = default; BackedStringView & operator=(BackedStringView && other) = default; bool isOwned() const { return std::holds_alternative<std::string>(data); } std::string toOwned() && { return isOwned() ? std::move(std::get<std::string>(data)) : std::string(std::get<std::string_view>(data)); } std::string_view operator*() const { return isOwned() ? std::get<std::string>(data) : std::get<std::string_view>(data); } Ptr operator->() const { return Ptr(**this); } }; }
2,955
C++
.h
98
26.153061
75
0.668781
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,224
users.hh
NixOS_nix/src/libutil/users.hh
#pragma once ///@file #include "types.hh" #ifndef _WIN32 # include <sys/types.h> #endif namespace nix { std::string getUserName(); #ifndef _WIN32 /** * @return the given user's home directory from /etc/passwd. */ Path getHomeOf(uid_t userId); #endif /** * @return $HOME or the user's home directory from /etc/passwd. */ Path getHome(); /** * @return $NIX_CACHE_HOME or $XDG_CACHE_HOME/nix or $HOME/.cache/nix. */ Path getCacheDir(); /** * @return $NIX_CONFIG_HOME or $XDG_CONFIG_HOME/nix or $HOME/.config/nix. */ Path getConfigDir(); /** * @return the directories to search for user configuration files */ std::vector<Path> getConfigDirs(); /** * @return $NIX_DATA_HOME or $XDG_DATA_HOME/nix or $HOME/.local/share/nix. */ Path getDataDir(); /** * @return $NIX_STATE_HOME or $XDG_STATE_HOME/nix or $HOME/.local/state/nix. */ Path getStateDir(); /** * Create the Nix state directory and return the path to it. */ Path createNixStateDir(); /** * Perform tilde expansion on a path, replacing tilde with the user's * home directory. */ std::string expandTilde(std::string_view path); /** * Is the current user UID 0 on Unix? * * Currently always false on Windows, but that may change. */ bool isRootUser(); }
1,243
C++
.h
54
21.296296
76
0.71185
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,225
file-content-address.hh
NixOS_nix/src/libutil/file-content-address.hh
#pragma once ///@file #include "source-accessor.hh" namespace nix { struct SourcePath; /** * An enumeration of the ways we can serialize file system * objects. * * See `file-system-object/content-address.md#serial` in the manual for * a user-facing description of this concept, but note that this type is also * used for storing or sending copies; not just for addressing. * Note also that there are other content addressing methods that don't * correspond to a serialisation method. */ enum struct FileSerialisationMethod : uint8_t { /** * Flat-file. The contents of a single file exactly. * * See `file-system-object/content-address.md#serial-flat` in the * manual. */ Flat, /** * Nix Archive. Serializes the file-system object in * Nix Archive format. * * See `file-system-object/content-address.md#serial-nix-archive` in * the manual. */ NixArchive, }; /** * Parse a `FileSerialisationMethod` by name. Choice of: * * - `flat`: `FileSerialisationMethod::Flat` * - `nar`: `FileSerialisationMethod::NixArchive` * * Opposite of `renderFileSerialisationMethod`. */ FileSerialisationMethod parseFileSerialisationMethod(std::string_view input); /** * Render a `FileSerialisationMethod` by name. * * Opposite of `parseFileSerialisationMethod`. */ std::string_view renderFileSerialisationMethod(FileSerialisationMethod method); /** * Dump a serialization of the given file system object. */ void dumpPath( const SourcePath & path, Sink & sink, FileSerialisationMethod method, PathFilter & filter = defaultPathFilter); /** * Restore a serialisation of the given file system object. * * \todo use an arbitrary `FileSystemObjectSink`. */ void restorePath( const Path & path, Source & source, FileSerialisationMethod method, bool startFsync = false); /** * Compute the hash of the given file system object according to the * given method. * * the hash is defined as (in pseudocode): * * ``` * hashString(ha, dumpPath(...)) * ``` */ HashResult hashPath( const SourcePath & path, FileSerialisationMethod method, HashAlgorithm ha, PathFilter & filter = defaultPathFilter); /** * An enumeration of the ways we can ingest file system * objects, producing a hash or digest. * * See `file-system-object/content-address.md` in the manual for a * user-facing description of this concept. */ enum struct FileIngestionMethod : uint8_t { /** * Hash `FileSerialisationMethod::Flat` serialisation. * * See `file-system-object/content-address.md#serial-flat` in the * manual. */ Flat, /** * Hash `FileSerialisationMethod::NixArchive` serialisation. * * See `file-system-object/content-address.md#serial-flat` in the * manual. */ NixArchive, /** * Git hashing. * * Part of `ExperimentalFeature::GitHashing`. * * See `file-system-object/content-address.md#serial-git` in the * manual. */ Git, }; /** * Parse a `FileIngestionMethod` by name. Choice of: * * - `flat`: `FileIngestionMethod::Flat` * - `nar`: `FileIngestionMethod::NixArchive` * - `git`: `FileIngestionMethod::Git` * * Opposite of `renderFileIngestionMethod`. */ FileIngestionMethod parseFileIngestionMethod(std::string_view input); /** * Render a `FileIngestionMethod` by name. * * Opposite of `parseFileIngestionMethod`. */ std::string_view renderFileIngestionMethod(FileIngestionMethod method); /** * Compute the hash of the given file system object according to the * given method, and for some ingestion methods, the size of the * serialisation. * * Unlike the other `hashPath`, this works on an arbitrary * `FileIngestionMethod` instead of `FileSerialisationMethod`, but * may not return the size as this is this is not a both simple and * useful defined for a merkle format. */ std::pair<Hash, std::optional<uint64_t>> hashPath( const SourcePath & path, FileIngestionMethod method, HashAlgorithm ha, PathFilter & filter = defaultPathFilter); }
4,108
C++
.h
142
25.704225
79
0.717325
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,226
exit.hh
NixOS_nix/src/libutil/exit.hh
#pragma once #include <exception> namespace nix { /** * Exit the program with a given exit code. */ class Exit : public std::exception { public: int status; Exit() : status(0) { } explicit Exit(int status) : status(status) { } virtual ~Exit(); }; }
271
C++
.h
15
15.6
50
0.662698
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,227
fs-sink.hh
NixOS_nix/src/libutil/fs-sink.hh
#pragma once ///@file #include "serialise.hh" #include "source-accessor.hh" #include "file-system.hh" namespace nix { /** * Actions on an open regular file in the process of creating it. * * See `FileSystemObjectSink::createRegularFile`. */ struct CreateRegularFileSink : Sink { virtual void isExecutable() = 0; /** * An optimization. By default, do nothing. */ virtual void preallocateContents(uint64_t size) { }; }; struct FileSystemObjectSink { virtual ~FileSystemObjectSink() = default; virtual void createDirectory(const CanonPath & path) = 0; /** * This function in general is no re-entrant. Only one file can be * written at a time. */ virtual void createRegularFile( const CanonPath & path, std::function<void(CreateRegularFileSink &)>) = 0; virtual void createSymlink(const CanonPath & path, const std::string & target) = 0; }; /** * An extension of `FileSystemObjectSink` that supports file types * that are not supported by Nix's FSO model. */ struct ExtendedFileSystemObjectSink : virtual FileSystemObjectSink { /** * Create a hard link. The target must be the path of a previously * encountered file relative to the root of the FSO. */ virtual void createHardlink(const CanonPath & path, const CanonPath & target) = 0; }; /** * Recursively copy file system objects from the source into the sink. */ void copyRecursive( SourceAccessor & accessor, const CanonPath & sourcePath, FileSystemObjectSink & sink, const CanonPath & destPath); /** * Ignore everything and do nothing */ struct NullFileSystemObjectSink : FileSystemObjectSink { void createDirectory(const CanonPath & path) override { } void createSymlink(const CanonPath & path, const std::string & target) override { } void createRegularFile( const CanonPath & path, std::function<void(CreateRegularFileSink &)>) override; }; /** * Write files at the given path */ struct RestoreSink : FileSystemObjectSink { std::filesystem::path dstPath; bool startFsync = false; explicit RestoreSink(bool startFsync) : startFsync{startFsync} { } void createDirectory(const CanonPath & path) override; void createRegularFile( const CanonPath & path, std::function<void(CreateRegularFileSink &)>) override; void createSymlink(const CanonPath & path, const std::string & target) override; }; /** * Restore a single file at the top level, passing along * `receiveContents` to the underlying `Sink`. For anything but a single * file, set `regular = true` so the caller can fail accordingly. */ struct RegularFileSink : FileSystemObjectSink { bool regular = true; Sink & sink; RegularFileSink(Sink & sink) : sink(sink) { } void createDirectory(const CanonPath & path) override { regular = false; } void createSymlink(const CanonPath & path, const std::string & target) override { regular = false; } void createRegularFile( const CanonPath & path, std::function<void(CreateRegularFileSink &)>) override; }; }
3,153
C++
.h
100
27.57
87
0.712211
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,228
memory-source-accessor.hh
NixOS_nix/src/libutil/memory-source-accessor.hh
#include "source-path.hh" #include "fs-sink.hh" #include "variant-wrapper.hh" namespace nix { /** * An source accessor for an in-memory file system. */ struct MemorySourceAccessor : virtual SourceAccessor { /** * In addition to being part of the implementation of * `MemorySourceAccessor`, this has a side benefit of nicely * defining what a "file system object" is in Nix. */ struct File { bool operator == (const File &) const noexcept; std::strong_ordering operator <=> (const File &) const noexcept; struct Regular { bool executable = false; std::string contents; bool operator == (const Regular &) const = default; auto operator <=> (const Regular &) const = default; }; struct Directory { using Name = std::string; std::map<Name, File, std::less<>> contents; bool operator == (const Directory &) const noexcept; // TODO libc++ 16 (used by darwin) missing `std::map::operator <=>`, can't do yet. bool operator < (const Directory &) const noexcept; }; struct Symlink { std::string target; bool operator == (const Symlink &) const = default; auto operator <=> (const Symlink &) const = default; }; using Raw = std::variant<Regular, Directory, Symlink>; Raw raw; MAKE_WRAPPER_CONSTRUCTOR(File); Stat lstat() const; }; File root { File::Directory {} }; bool operator == (const MemorySourceAccessor &) const noexcept = default; bool operator < (const MemorySourceAccessor & other) const noexcept { return root < other.root; } std::string readFile(const CanonPath & path) override; bool pathExists(const CanonPath & path) override; std::optional<Stat> maybeLstat(const CanonPath & path) override; DirEntries readDirectory(const CanonPath & path) override; std::string readLink(const CanonPath & path) override; /** * @param create If present, create this file and any parent directories * that are needed. * * Return null if * * - `create = false`: File does not exist. * * - `create = true`: some parent file was not a dir, so couldn't * look/create inside. */ File * open(const CanonPath & path, std::optional<File> create); SourcePath addFile(CanonPath path, std::string && contents); }; inline bool MemorySourceAccessor::File::Directory::operator == ( const MemorySourceAccessor::File::Directory &) const noexcept = default; inline bool MemorySourceAccessor::File::Directory::operator < ( const MemorySourceAccessor::File::Directory & other) const noexcept { return contents < other.contents; } inline bool MemorySourceAccessor::File::operator == ( const MemorySourceAccessor::File &) const noexcept = default; inline std::strong_ordering MemorySourceAccessor::File::operator <=> ( const MemorySourceAccessor::File &) const noexcept = default; /** * Write to a `MemorySourceAccessor` at the given path */ struct MemorySink : FileSystemObjectSink { MemorySourceAccessor & dst; MemorySink(MemorySourceAccessor & dst) : dst(dst) { } void createDirectory(const CanonPath & path) override; void createRegularFile( const CanonPath & path, std::function<void(CreateRegularFileSink &)>) override; void createSymlink(const CanonPath & path, const std::string & target) override; }; }
3,544
C++
.h
89
33.606742
94
0.664917
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,229
topo-sort.hh
NixOS_nix/src/libutil/topo-sort.hh
#pragma once ///@file #include "error.hh" namespace nix { template<typename T> std::vector<T> topoSort(std::set<T> items, std::function<std::set<T>(const T &)> getChildren, std::function<Error(const T &, const T &)> makeCycleError) { std::vector<T> sorted; std::set<T> visited, parents; std::function<void(const T & path, const T * parent)> dfsVisit; dfsVisit = [&](const T & path, const T * parent) { if (parents.count(path)) throw makeCycleError(path, *parent); if (!visited.insert(path).second) return; parents.insert(path); std::set<T> references = getChildren(path); for (auto & i : references) /* Don't traverse into items that don't exist in our starting set. */ if (i != path && items.count(i)) dfsVisit(i, &path); sorted.push_back(path); parents.erase(path); }; for (auto & i : items) dfsVisit(i, nullptr); std::reverse(sorted.begin(), sorted.end()); return sorted; } }
1,044
C++
.h
30
28.3
81
0.606394
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
11,230
thread-pool.hh
NixOS_nix/src/libutil/thread-pool.hh
#pragma once ///@file #include "error.hh" #include "sync.hh" #include <queue> #include <functional> #include <thread> #include <map> #include <atomic> namespace nix { MakeError(ThreadPoolShutDown, Error); /** * A simple thread pool that executes a queue of work items * (lambdas). */ class ThreadPool { public: ThreadPool(size_t maxThreads = 0); ~ThreadPool(); /** * An individual work item. * * \todo use std::packaged_task? */ typedef std::function<void()> work_t; /** * Enqueue a function to be executed by the thread pool. */ void enqueue(const work_t & t); /** * Execute work items until the queue is empty. * * \note Note that work items are allowed to add new items to the * queue; this is handled correctly. * * Queue processing stops prematurely if any work item throws an * exception. This exception is propagated to the calling thread. If * multiple work items throw an exception concurrently, only one * item is propagated; the others are printed on stderr and * otherwise ignored. */ void process(); private: size_t maxThreads; struct State { std::queue<work_t> pending; size_t active = 0; std::exception_ptr exception; std::vector<std::thread> workers; bool draining = false; }; std::atomic_bool quit{false}; Sync<State> state_; std::condition_variable work; void doWork(bool mainThread); void shutdown(); }; /** * Process in parallel a set of items of type T that have a partial * ordering between them. Thus, any item is only processed after all * its dependencies have been processed. */ template<typename T> void processGraph( ThreadPool & pool, const std::set<T> & nodes, std::function<std::set<T>(const T &)> getEdges, std::function<void(const T &)> processNode) { struct Graph { std::set<T> left; std::map<T, std::set<T>> refs, rrefs; }; Sync<Graph> graph_(Graph{nodes, {}, {}}); std::function<void(const T &)> worker; worker = [&](const T & node) { { auto graph(graph_.lock()); auto i = graph->refs.find(node); if (i == graph->refs.end()) goto getRefs; goto doWork; } getRefs: { auto refs = getEdges(node); refs.erase(node); { auto graph(graph_.lock()); for (auto & ref : refs) if (graph->left.count(ref)) { graph->refs[node].insert(ref); graph->rrefs[ref].insert(node); } if (graph->refs[node].empty()) goto doWork; } } return; doWork: processNode(node); /* Enqueue work for all nodes that were waiting on this one and have no unprocessed dependencies. */ { auto graph(graph_.lock()); for (auto & rref : graph->rrefs[node]) { auto & refs(graph->refs[rref]); auto i = refs.find(node); assert(i != refs.end()); refs.erase(i); if (refs.empty()) pool.enqueue(std::bind(worker, rref)); } graph->left.erase(node); graph->refs.erase(node); graph->rrefs.erase(node); } }; for (auto & node : nodes) pool.enqueue(std::bind(worker, std::ref(node))); pool.process(); if (!graph_.lock()->left.empty()) throw Error("graph processing incomplete (cyclic reference?)"); } }
3,727
C++
.h
127
21.677165
72
0.565303
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,231
processes.hh
NixOS_nix/src/libutil/processes.hh
#pragma once ///@file #include "types.hh" #include "error.hh" #include "file-descriptor.hh" #include "logging.hh" #include "ansicolor.hh" #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #include <signal.h> #include <atomic> #include <functional> #include <map> #include <sstream> #include <optional> namespace nix { struct Sink; struct Source; class Pid { #ifndef _WIN32 pid_t pid = -1; bool separatePG = false; int killSignal = SIGKILL; #else AutoCloseFD pid = INVALID_DESCRIPTOR; #endif public: Pid(); #ifndef _WIN32 Pid(pid_t pid); void operator =(pid_t pid); operator pid_t(); #else Pid(AutoCloseFD pid); void operator =(AutoCloseFD pid); #endif ~Pid(); int kill(); int wait(); // TODO: Implement for Windows #ifndef _WIN32 void setSeparatePG(bool separatePG); void setKillSignal(int signal); pid_t release(); #endif }; #ifndef _WIN32 /** * Kill all processes running under the specified uid by sending them * a SIGKILL. */ void killUser(uid_t uid); #endif /** * Fork a process that runs the given function, and return the child * pid to the caller. */ struct ProcessOptions { std::string errorPrefix = ""; bool dieWithParent = true; bool runExitHandlers = false; bool allowVfork = false; /** * use clone() with the specified flags (Linux only) */ int cloneFlags = 0; }; #ifndef _WIN32 pid_t startProcess(std::function<void()> fun, const ProcessOptions & options = ProcessOptions()); #endif /** * Run a program and return its stdout in a string (i.e., like the * shell backtick operator). */ std::string runProgram(Path program, bool lookupPath = false, const Strings & args = Strings(), const std::optional<std::string> & input = {}, bool isInteractive = false); struct RunOptions { Path program; bool lookupPath = true; Strings args; #ifndef _WIN32 std::optional<uid_t> uid; std::optional<uid_t> gid; #endif std::optional<Path> chdir; std::optional<std::map<std::string, std::string>> environment; std::optional<std::string> input; Source * standardIn = nullptr; Sink * standardOut = nullptr; bool mergeStderrToStdout = false; bool isInteractive = false; }; std::pair<int, std::string> runProgram(RunOptions && options); void runProgram2(const RunOptions & options); class ExecError : public Error { public: int status; template<typename... Args> ExecError(int status, const Args & ... args) : Error(args...), status(status) { } }; /** * Convert the exit status of a child as returned by wait() into an * error string. */ std::string statusToString(int status); bool statusOk(int status); }
2,750
C++
.h
116
20.844828
97
0.698698
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,232
serialise.hh
NixOS_nix/src/libutil/serialise.hh
#pragma once ///@file #include <memory> #include <type_traits> #include "types.hh" #include "util.hh" #include "file-descriptor.hh" namespace boost::context { struct stack_context; } namespace nix { /** * Abstract destination of binary data. */ struct Sink { virtual ~Sink() { } virtual void operator () (std::string_view data) = 0; virtual bool good() { return true; } }; /** * Just throws away data. */ struct NullSink : Sink { void operator () (std::string_view data) override { } }; struct FinishSink : virtual Sink { virtual void finish() = 0; }; /** * A buffered abstract sink. Warning: a BufferedSink should not be * used from multiple threads concurrently. */ struct BufferedSink : virtual Sink { size_t bufSize, bufPos; std::unique_ptr<char[]> buffer; BufferedSink(size_t bufSize = 32 * 1024) : bufSize(bufSize), bufPos(0), buffer(nullptr) { } void operator () (std::string_view data) override; void flush(); protected: virtual void writeUnbuffered(std::string_view data) = 0; }; /** * Abstract source of binary data. */ struct Source { virtual ~Source() { } /** * Store exactly ‘len’ bytes in the buffer pointed to by ‘data’. * It blocks until all the requested data is available, or throws * an error if it is not going to be available. */ void operator () (char * data, size_t len); void operator () (std::string_view data); /** * Store up to ‘len’ in the buffer pointed to by ‘data’, and * return the number of bytes stored. It blocks until at least * one byte is available. */ virtual size_t read(char * data, size_t len) = 0; virtual bool good() { return true; } void drainInto(Sink & sink); std::string drain(); }; /** * A buffered abstract source. Warning: a BufferedSource should not be * used from multiple threads concurrently. */ struct BufferedSource : Source { size_t bufSize, bufPosIn, bufPosOut; std::unique_ptr<char[]> buffer; BufferedSource(size_t bufSize = 32 * 1024) : bufSize(bufSize), bufPosIn(0), bufPosOut(0), buffer(nullptr) { } size_t read(char * data, size_t len) override; /** * Return true if the buffer is not empty. */ bool hasData(); protected: /** * Underlying read call, to be overridden. */ virtual size_t readUnbuffered(char * data, size_t len) = 0; }; /** * A sink that writes data to a file descriptor. */ struct FdSink : BufferedSink { Descriptor fd; size_t written = 0; FdSink() : fd(INVALID_DESCRIPTOR) { } FdSink(Descriptor fd) : fd(fd) { } FdSink(FdSink&&) = default; FdSink & operator=(FdSink && s) { flush(); fd = s.fd; s.fd = INVALID_DESCRIPTOR; written = s.written; return *this; } ~FdSink(); void writeUnbuffered(std::string_view data) override; bool good() override; private: bool _good = true; }; /** * A source that reads data from a file descriptor. */ struct FdSource : BufferedSource { Descriptor fd; size_t read = 0; BackedStringView endOfFileError{"unexpected end-of-file"}; FdSource() : fd(INVALID_DESCRIPTOR) { } FdSource(Descriptor fd) : fd(fd) { } FdSource(FdSource &&) = default; FdSource & operator=(FdSource && s) = default; bool good() override; /** * Return true if the buffer is not empty after a non-blocking * read. */ bool hasData(); protected: size_t readUnbuffered(char * data, size_t len) override; private: bool _good = true; }; /** * A sink that writes data to a string. */ struct StringSink : Sink { std::string s; StringSink() { } explicit StringSink(const size_t reservedSize) { s.reserve(reservedSize); }; StringSink(std::string && s) : s(std::move(s)) { }; void operator () (std::string_view data) override; }; /** * A source that reads data from a string. */ struct StringSource : Source { std::string_view s; size_t pos; // NOTE: Prevent unintentional dangling views when an implicit conversion // from std::string -> std::string_view occurs when the string is passed // by rvalue. StringSource(std::string &&) = delete; StringSource(std::string_view s) : s(s), pos(0) { } StringSource(const std::string& str): StringSource(std::string_view(str)) {} size_t read(char * data, size_t len) override; }; /** * A sink that writes all incoming data to two other sinks. */ struct TeeSink : Sink { Sink & sink1, & sink2; TeeSink(Sink & sink1, Sink & sink2) : sink1(sink1), sink2(sink2) { } virtual void operator () (std::string_view data) override { sink1(data); sink2(data); } }; /** * Adapter class of a Source that saves all data read to a sink. */ struct TeeSource : Source { Source & orig; Sink & sink; TeeSource(Source & orig, Sink & sink) : orig(orig), sink(sink) { } size_t read(char * data, size_t len) override { size_t n = orig.read(data, len); sink({data, n}); return n; } }; /** * A reader that consumes the original Source until 'size'. */ struct SizedSource : Source { Source & orig; size_t remain; SizedSource(Source & orig, size_t size) : orig(orig), remain(size) { } size_t read(char * data, size_t len) override { if (this->remain <= 0) { throw EndOfFile("sized: unexpected end-of-file"); } len = std::min(len, this->remain); size_t n = this->orig.read(data, len); this->remain -= n; return n; } /** * Consume the original source until no remain data is left to consume. */ size_t drainAll() { std::vector<char> buf(8192); size_t sum = 0; while (this->remain > 0) { size_t n = read(buf.data(), buf.size()); sum += n; } return sum; } }; /** * A sink that that just counts the number of bytes given to it */ struct LengthSink : Sink { uint64_t length = 0; void operator () (std::string_view data) override { length += data.size(); } }; /** * A wrapper source that counts the number of bytes read from it. */ struct LengthSource : Source { Source & next; LengthSource(Source & next) : next(next) { } uint64_t total = 0; size_t read(char * data, size_t len) override { auto n = next.read(data, len); total += n; return n; } }; /** * Convert a function into a sink. */ struct LambdaSink : Sink { typedef std::function<void(std::string_view data)> lambda_t; lambda_t lambda; LambdaSink(const lambda_t & lambda) : lambda(lambda) { } void operator () (std::string_view data) override { lambda(data); } }; /** * Convert a function into a source. */ struct LambdaSource : Source { typedef std::function<size_t(char *, size_t)> lambda_t; lambda_t lambda; LambdaSource(const lambda_t & lambda) : lambda(lambda) { } size_t read(char * data, size_t len) override { return lambda(data, len); } }; /** * Chain two sources together so after the first is exhausted, the second is * used */ struct ChainSource : Source { Source & source1, & source2; bool useSecond = false; ChainSource(Source & s1, Source & s2) : source1(s1), source2(s2) { } size_t read(char * data, size_t len) override; }; std::unique_ptr<FinishSink> sourceToSink(std::function<void(Source &)> fun); /** * Convert a function that feeds data into a Sink into a Source. The * Source executes the function as a coroutine. */ std::unique_ptr<Source> sinkToSource( std::function<void(Sink &)> fun, std::function<void()> eof = []() { throw EndOfFile("coroutine has finished"); }); void writePadding(size_t len, Sink & sink); void writeString(std::string_view s, Sink & sink); inline Sink & operator << (Sink & sink, uint64_t n) { unsigned char buf[8]; buf[0] = n & 0xff; buf[1] = (n >> 8) & 0xff; buf[2] = (n >> 16) & 0xff; buf[3] = (n >> 24) & 0xff; buf[4] = (n >> 32) & 0xff; buf[5] = (n >> 40) & 0xff; buf[6] = (n >> 48) & 0xff; buf[7] = (unsigned char) (n >> 56) & 0xff; sink({(char *) buf, sizeof(buf)}); return sink; } Sink & operator << (Sink & in, const Error & ex); Sink & operator << (Sink & sink, std::string_view s); Sink & operator << (Sink & sink, const Strings & s); Sink & operator << (Sink & sink, const StringSet & s); MakeError(SerialisationError, Error); template<typename T> T readNum(Source & source) { unsigned char buf[8]; source((char *) buf, sizeof(buf)); auto n = readLittleEndian<uint64_t>(buf); if (n > (uint64_t) std::numeric_limits<T>::max()) throw SerialisationError("serialised integer %d is too large for type '%s'", n, typeid(T).name()); return (T) n; } inline unsigned int readInt(Source & source) { return readNum<unsigned int>(source); } inline uint64_t readLongLong(Source & source) { return readNum<uint64_t>(source); } void readPadding(size_t len, Source & source); size_t readString(char * buf, size_t max, Source & source); std::string readString(Source & source, size_t max = std::numeric_limits<size_t>::max()); template<class T> T readStrings(Source & source); Source & operator >> (Source & in, std::string & s); template<typename T> Source & operator >> (Source & in, T & n) { n = readNum<T>(in); return in; } template<typename T> Source & operator >> (Source & in, bool & b) { b = readNum<uint64_t>(in); return in; } Error readError(Source & source); /** * An adapter that converts a std::basic_istream into a source. */ struct StreamToSourceAdapter : Source { std::shared_ptr<std::basic_istream<char>> istream; StreamToSourceAdapter(std::shared_ptr<std::basic_istream<char>> istream) : istream(istream) { } size_t read(char * data, size_t len) override { if (!istream->read(data, len)) { if (istream->eof()) { if (istream->gcount() == 0) throw EndOfFile("end of file"); } else throw Error("I/O error in StreamToSourceAdapter"); } return istream->gcount(); } }; /** * A source that reads a distinct format of concatenated chunks back into its * logical form, in order to guarantee a known state to the original stream, * even in the event of errors. * * Use with FramedSink, which also allows the logical stream to be terminated * in the event of an exception. */ struct FramedSource : Source { Source & from; bool eof = false; std::vector<char> pending; size_t pos = 0; FramedSource(Source & from) : from(from) { } ~FramedSource() { try { if (!eof) { while (true) { auto n = readInt(from); if (!n) break; std::vector<char> data(n); from(data.data(), n); } } } catch (...) { ignoreExceptionInDestructor(); } } size_t read(char * data, size_t len) override { if (eof) throw EndOfFile("reached end of FramedSource"); if (pos >= pending.size()) { size_t len = readInt(from); if (!len) { eof = true; return 0; } pending = std::vector<char>(len); pos = 0; from(pending.data(), len); } auto n = std::min(len, pending.size() - pos); memcpy(data, pending.data() + pos, n); pos += n; return n; } }; /** * Write as chunks in the format expected by FramedSource. * * The `checkError` function can be used to terminate the stream when you * detect that an error has occurred. It does so by throwing an exception. */ struct FramedSink : nix::BufferedSink { BufferedSink & to; std::function<void()> checkError; FramedSink(BufferedSink & to, std::function<void()> && checkError) : to(to), checkError(checkError) { } ~FramedSink() { try { to << 0; to.flush(); } catch (...) { ignoreExceptionInDestructor(); } } void writeUnbuffered(std::string_view data) override { /* Don't send more data if an error has occured. */ checkError(); to << data.size(); to(data); }; }; }
12,655
C++
.h
462
22.482684
106
0.61381
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,233
config-global.hh
NixOS_nix/src/libutil/config-global.hh
#pragma once ///@file #include "config.hh" namespace nix { struct GlobalConfig : public AbstractConfig { typedef std::vector<Config *> ConfigRegistrations; static ConfigRegistrations * configRegistrations; bool set(const std::string & name, const std::string & value) override; void getSettings(std::map<std::string, SettingInfo> & res, bool overriddenOnly = false) override; void resetOverridden() override; nlohmann::json toJSON() override; std::string toKeyValue() override; void convertToArgs(Args & args, const std::string & category) override; struct Register { Register(Config * config); }; }; extern GlobalConfig globalConfig; }
701
C++
.h
21
29.333333
101
0.733533
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,234
namespaces.hh
NixOS_nix/src/libutil/linux/namespaces.hh
#pragma once ///@file #include <optional> #include "types.hh" namespace nix { /** * Save the current mount namespace. Ignored if called more than * once. */ void saveMountNamespace(); /** * Restore the mount namespace saved by saveMountNamespace(). Ignored * if saveMountNamespace() was never called. */ void restoreMountNamespace(); /** * Cause this thread to try to not share any FS attributes with the main * thread, because this causes setns() in restoreMountNamespace() to * fail. * * This is best effort -- EPERM and ENOSYS failures are just ignored. */ void tryUnshareFilesystem(); bool userNamespacesSupported(); bool mountAndPidNamespacesSupported(); }
683
C++
.h
26
24.461538
72
0.766975
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,235
cgroup.hh
NixOS_nix/src/libutil/linux/cgroup.hh
#pragma once ///@file #include <chrono> #include <optional> #include "types.hh" namespace nix { std::optional<Path> getCgroupFS(); std::map<std::string, std::string> getCgroups(const Path & cgroupFile); struct CgroupStats { std::optional<std::chrono::microseconds> cpuUser, cpuSystem; }; /** * Destroy the cgroup denoted by 'path'. The postcondition is that * 'path' does not exist, and thus any processes in the cgroup have * been killed. Also return statistics from the cgroup just before * destruction. */ CgroupStats destroyCgroup(const Path & cgroup); std::string getCurrentCgroup(); /** * Get the cgroup that should be used as the parent when creating new * sub-cgroups. The first time this is called, the current cgroup will be * returned, and then all subsequent calls will return the original cgroup. */ std::string getRootCgroup(); }
867
C++
.h
27
30.259259
75
0.762651
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,236
root.hh
NixOS_nix/src/libutil/args/root.hh
#pragma once #include "args.hh" namespace nix { /** * The concrete implementation of a collection of completions. * * This is exposed so that the main entry point can print out the * collected completions. */ struct Completions final : AddCompletions { std::set<Completion> completions; Type type = Type::Normal; void setType(Type type) override; void add(std::string completion, std::string description = "") override; }; /** * The outermost Args object. This is the one we will actually parse a command * line with, whereas the inner ones (if they exists) are subcommands (and this * is also a MultiCommand or something like it). * * This Args contains completions state shared between it and all of its * descendent Args. */ class RootArgs : virtual public Args { protected: /** * @brief The command's "working directory", but only set when top level. * * Use getCommandBaseDir() to get the directory regardless of whether this * is a top-level command or subcommand. * * @see getCommandBaseDir() */ Path commandBaseDir = "."; public: /** Parse the command line, throwing a UsageError if something goes * wrong. */ void parseCmdline(const Strings & cmdline, bool allowShebang = false); std::shared_ptr<Completions> completions; Path getCommandBaseDir() const override; protected: friend class Args; /** * A pointer to the completion and its two arguments; a thunk; */ struct DeferredCompletion { const CompleterClosure & completer; size_t n; std::string prefix; }; /** * Completions are run after all args and flags are parsed, so completions * of earlier arguments can benefit from later arguments. */ std::vector<DeferredCompletion> deferredCompletions; /** * Experimental features needed when parsing args. These are checked * after flag parsing is completed in order to support enabling * experimental features coming after the flag that needs the * experimental feature. */ std::set<ExperimentalFeature> flagExperimentalFeatures; private: std::optional<std::string> needsCompletion(std::string_view s); }; }
2,239
C++
.h
69
28.217391
79
0.712163
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,237
local-keys.hh
NixOS_nix/src/libutil/signature/local-keys.hh
#pragma once ///@file #include "types.hh" #include <map> namespace nix { /** * Except where otherwise noted, Nix serializes keys and signatures in * the form: * * ``` * <name>:<key/signature-in-Base64> * ``` */ struct BorrowedCryptoValue { std::string_view name; std::string_view payload; /** * This splits on the colon, the user can then separated decode the * Base64 payload separately. */ static BorrowedCryptoValue parse(std::string_view); }; struct Key { std::string name; std::string key; std::string to_string() const; protected: /** * Construct Key from a string in the format * ‘<name>:<key-in-base64>’. * * @param sensitiveValue Avoid displaying the raw Base64 in error * messages to avoid leaking private keys. */ Key(std::string_view s, bool sensitiveValue); Key(std::string_view name, std::string && key) : name(name), key(std::move(key)) { } }; struct PublicKey; struct SecretKey : Key { SecretKey(std::string_view s); /** * Return a detached signature of the given string. */ std::string signDetached(std::string_view s) const; PublicKey toPublicKey() const; static SecretKey generate(std::string_view name); private: SecretKey(std::string_view name, std::string && key) : Key(name, std::move(key)) { } }; struct PublicKey : Key { PublicKey(std::string_view data); /** * @return true iff `sig` and this key's names match, and `sig` is a * correct signature over `data` using the given public key. */ bool verifyDetached(std::string_view data, std::string_view sigs) const; /** * @return true iff `sig` is a correct signature over `data` using the * given public key. * * @param just the Base64 signature itself, not a colon-separated pair of a * public key name and signature. */ bool verifyDetachedAnon(std::string_view data, std::string_view sigs) const; private: PublicKey(std::string_view name, std::string && key) : Key(name, std::move(key)) { } friend struct SecretKey; }; /** * Map from key names to public keys */ typedef std::map<std::string, PublicKey> PublicKeys; /** * @return true iff ‘sig’ is a correct signature over ‘data’ using one * of the given public keys. */ bool verifyDetached(std::string_view data, std::string_view sig, const PublicKeys & publicKeys); }
2,457
C++
.h
84
25.119048
96
0.671086
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,238
signer.hh
NixOS_nix/src/libutil/signature/signer.hh
#pragma once #include "types.hh" #include "signature/local-keys.hh" #include <map> #include <optional> namespace nix { /** * An abstract signer * * Derive from this class to implement a custom signature scheme. * * It is only necessary to implement signature of bytes and provide a * public key. */ struct Signer { virtual ~Signer() = default; /** * Sign the given data, creating a (detached) signature. * * @param data data to be signed. * * @return the [detached * signature](https://en.wikipedia.org/wiki/Detached_signature), * i.e. just the signature itself without a copy of the signed data. */ virtual std::string signDetached(std::string_view data) const = 0; /** * View the public key associated with this `Signer`. */ virtual const PublicKey & getPublicKey() = 0; }; using Signers = std::map<std::string, Signer*>; /** * Local signer * * The private key is held in this machine's RAM */ struct LocalSigner : Signer { LocalSigner(SecretKey && privateKey); std::string signDetached(std::string_view s) const override; const PublicKey & getPublicKey() override; private: SecretKey privateKey; PublicKey publicKey; }; }
1,239
C++
.h
48
22.4375
72
0.694397
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,239
monitor-fd.hh
NixOS_nix/src/libutil/unix/monitor-fd.hh
#pragma once ///@file #include <thread> #include <atomic> #include <cstdlib> #include <poll.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> #include "signals.hh" namespace nix { class MonitorFdHup { private: std::thread thread; public: MonitorFdHup(int fd) { thread = std::thread([fd]() { while (true) { /* Wait indefinitely until a POLLHUP occurs. */ struct pollfd fds[1]; fds[0].fd = fd; /* Polling for no specific events (i.e. just waiting for an error/hangup) doesn't work on macOS anymore. So wait for read events and ignore them. */ fds[0].events = #ifdef __APPLE__ POLLRDNORM #else 0 #endif ; auto count = poll(fds, 1, -1); if (count == -1) unreachable(); /* This shouldn't happen, but can on macOS due to a bug. See rdar://37550628. This may eventually need a delay or further coordination with the main thread if spinning proves too harmful. */ if (count == 0) continue; if (fds[0].revents & POLLHUP) { unix::triggerInterrupt(); break; } /* This will only happen on macOS. We sleep a bit to avoid waking up too often if the client is sending input. */ sleep(1); } }); }; ~MonitorFdHup() { pthread_cancel(thread.native_handle()); thread.join(); } }; }
1,849
C++
.h
62
18
72
0.463662
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,240
signals-impl.hh
NixOS_nix/src/libutil/unix/signals-impl.hh
#pragma once /** * @file * * Implementation of some inline definitions for Unix signals, and also * some extra Unix-only interfaces. * * (The only reason everything about signals isn't Unix-only is some * no-op definitions are provided on Windows to avoid excess CPP in * downstream code.) */ #include "types.hh" #include "error.hh" #include "logging.hh" #include "ansicolor.hh" #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #include <signal.h> #include <boost/lexical_cast.hpp> #include <atomic> #include <functional> #include <map> #include <sstream> #include <optional> namespace nix { /* User interruption. */ namespace unix { extern std::atomic<bool> _isInterrupted; extern thread_local std::function<bool()> interruptCheck; void _interrupted(); /** * Sets the signal mask. Like saveSignalMask() but for a signal set that doesn't * necessarily match the current thread's mask. * See saveSignalMask() to set the saved mask to the current mask. */ void setChildSignalMask(sigset_t *sigs); /** * Start a thread that handles various signals. Also block those signals * on the current thread (and thus any threads created by it). * Saves the signal mask before changing the mask to block those signals. * See saveSignalMask(). */ void startSignalHandlerThread(); /** * Saves the signal mask, which is the signal mask that nix will restore * before creating child processes. * See setChildSignalMask() to set an arbitrary signal mask instead of the * current mask. */ void saveSignalMask(); /** * To use in a process that already called `startSignalHandlerThread()` * or `saveSignalMask()` first. */ void restoreSignals(); void triggerInterrupt(); } static inline void setInterrupted(bool isInterrupted) { unix::_isInterrupted = isInterrupted; } static inline bool getInterrupted() { return unix::_isInterrupted; } /** * Throw `Interrupted` exception if the process has been interrupted. * * Call this in long-running loops and between slow operations to terminate * them as needed. */ void inline checkInterrupt() { using namespace unix; if (_isInterrupted || (interruptCheck && interruptCheck())) _interrupted(); } /** * A RAII class that causes the current thread to receive SIGUSR1 when * the signal handler thread receives SIGINT. That is, this allows * SIGINT to be multiplexed to multiple threads. */ struct ReceiveInterrupts { pthread_t target; std::unique_ptr<InterruptCallback> callback; ReceiveInterrupts() : target(pthread_self()) , callback(createInterruptCallback([&]() { pthread_kill(target, SIGUSR1); })) { } }; }
2,682
C++
.h
94
26.319149
85
0.748928
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,241
windows-error.hh
NixOS_nix/src/libutil/windows/windows-error.hh
#pragma once ///@file #include <errhandlingapi.h> #include "error.hh" namespace nix::windows { /** * Windows Error type. * * Unless you need to catch a specific error number, don't catch this in * portable code. Catch `SystemError` instead. */ class WinError : public SystemError { public: DWORD lastError; /** * Construct using the explicitly-provided error number. * `FormatMessageA` will be used to try to add additional * information to the message. */ template<typename... Args> WinError(DWORD lastError, const Args & ... args) : SystemError(""), lastError(lastError) { auto hf = HintFmt(args...); err.msg = HintFmt("%1%: %2%", Uncolored(hf.str()), renderError(lastError)); } /** * Construct using `GetLastError()` and the ambient "last error". * * Be sure to not perform another last-error-modifying operation * before calling this constructor! */ template<typename... Args> WinError(const Args & ... args) : WinError(GetLastError(), args ...) { } private: std::string renderError(DWORD lastError); }; }
1,149
C++
.h
42
23.047619
83
0.657559
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,242
windows-async-pipe.hh
NixOS_nix/src/libutil/windows/windows-async-pipe.hh
#pragma once ///@file #include "file-descriptor.hh" namespace nix::windows { /*** * An "async pipe" is a pipe that supports I/O Completion Ports so * multiple pipes can be listened too. * * Unfortunately, only named pipes support that on windows, so we use * those with randomized temp file names. */ class AsyncPipe { public: AutoCloseFD writeSide, readSide; OVERLAPPED overlapped; DWORD got; std::vector<unsigned char> buffer; void createAsyncPipe(HANDLE iocp); void close(); }; }
518
C++
.h
22
20.954545
69
0.735234
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,243
signals-impl.hh
NixOS_nix/src/libutil/windows/signals-impl.hh
#pragma once ///@file #include "types.hh" namespace nix { /* User interruption. */ static inline void setInterrupted(bool isInterrupted) { /* Do nothing for now */ } static inline bool getInterrupted() { return false; } inline void setInterruptThrown() { /* Do nothing for now */ } void inline checkInterrupt() { /* Do nothing for now */ } /** * Does nothing, unlike Unix counterpart, but allows avoiding C++ */ struct ReceiveInterrupts { /** * Explicit destructor avoids dead code warnings. */ ~ReceiveInterrupts() {} }; }
569
C++
.h
32
15.375
65
0.702652
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false