Programming Search⌘K

Conceptintro

Package manager

Also called package manager, package management system, dependency manager, language package manager, system package manager, install a package.

A package manager installs, updates and removes packages, and the packages that they depend on. Language package managers serve one language; system package managers install programs.

Applies to
core-languages

Idea

A program uses code that other people wrote. To build or run it, you need that code in the right version, and the code that it uses in turn. A package manager is the tool that gets this code, installs it, updates it and removes it. The Cargo Book gives the reason for one: most programs depend on external libraries, and so they depend transitively on the dependencies of those libraries. To get the correct versions of all of them and keep them up to date by hand "would be hard and error-prone".1

A package is the unit that the tool installs. It holds files, a name, a version and a list of the packages that it needs. A Debian binary package holds "executables, configuration files, man/info pages, copyright information, and other documentation", and its control file lists its dependencies.2 A Rust package has the file Cargo.toml with the same kind of information.1

There are two large groups:

  • Language package managers install libraries for one language into one project. Examples are Cargo for Rust, which "is the Rust package manager", pip, which "is the package installer for Python", and npm for JavaScript.134
  • System package managers install programs and shared libraries for the whole operating system. On Debian and Ubuntu, dpkg installs a .deb file, and apt is the front end that finds packages and their dependencies.25

The smallest use is one command. With apt, apt install installs a package and the packages that it depends on, and apt remove removes it.5

How it works

A package manager does five jobs.

  1. Find. It reads an index of the available packages from a source, which is called a registry, a repository or an index. apt update downloads this index "from all configured sources".5 pip installs packages from the Python Package Index and other indexes.3
  2. Resolve. It reads the dependencies of the package, then the dependencies of those dependencies, and it chooses one version of each package that satisfies all the requirements. This step is hard in general. Abate and others show that dependency solving is NP-complete "in all non-trivial component models".6 The Dependency resolution page explains the algorithms.
  3. Fetch and install. It downloads each package and puts its files in place, dependencies first. A Debian package can name another package that "absolutely must be installed" before it runs, and it can name packages that it conflicts with.2
  4. Record. It writes down what it installed, and why. apt keeps a mark for each package that it installed only to satisfy a dependency.5 A language package manager writes a lock file with the exact versions; see Lock files.
  5. Remove. It removes a package only if no other installed package needs it. apt autoremove removes packages "that were automatically installed to satisfy dependencies for other packages and are now no longer needed".5

The examples below show these jobs on a small registry. app needs web and log, web needs http and log, and cli needs log. The program installs app and cli, refuses to remove log while other packages need it, removes app, and then removes the dependencies that nothing needs.

In languages

LanguageVerdictNote
PythonIdiom
C++IdiomA std::map for the registry and a std::map for the installed packages. Alternative: The Java example.
JavaIdiom
CIdiomAn array of package structs with a flag for each, and a recursive install function. Alternative: The Go example.
C#Idiom
JavaScriptIdiomA Map for the registry and a Map for the installed packages, with a recursive install, as in the Python example. Alternative: The Python example.
TypeScriptIdiomAs in JavaScript, with the type Map<string, string[]> for the registry. Alternative: The C# example.
GoIdiom
RustIdiomA HashMap for the registry and a BTreeMap for the installed packages, which keeps the names in order. Alternative: The Go example.
KotlinIdiomMapOf for the registry and a sortedMapOf for the installed packages. Alternative: The Java example.
SQLDoes not applyA query does not install packages; a table of packages and a table of dependencies can store the same data.
BashIdiomThe package managers are commands, such as apt install, apt remove and apt autoremove, so a script calls them. Alternative: The Python example.
PowerShellIdiomHashtables for the registry and the installed packages, and a recursive function; Install-Package and winget are commands. Alternative: The C# example.
HTMLDoes not applyMarkup does not install packages.
CSSDoes not applyStyle rules do not install packages.
Regular expressionsDoes not applyA pattern does not install packages.

Each example keeps a map from each installed package to a flag: true if the user asked for the package, false if it came as a dependency. This is the same information as the automatic mark of apt.5 install installs the dependencies first, remove refuses to break an installed package, and autoremove repeats until no unused dependency is left.

PythonGitHub
# A tiny package manager: install with dependencies, refuse to break them, and remove unused ones.
REGISTRY = {
    "app": ["web", "log"],
    "web": ["http", "log"],
    "http": [],
    "log": [],
    "cli": ["log"],
}
installed = {}  # name -> True if the user asked for it, False if it came as a dependency


def install(name, asked=True):
    if name in installed:
        installed[name] = installed[name] or asked
        return
    for dep in REGISTRY[name]:
        install(dep, asked=False)
    installed[name] = asked
    print("  install", name, "(asked)" if asked else "(dependency)")


def needed_by(name):
    return sorted(p for p in installed if name in REGISTRY[p])


def remove(name):
    users = needed_by(name)
    if users:
        print("  error:", name, "is needed by", ", ".join(users))
        return
    del installed[name]
    print("  remove", name)


def autoremove():
    changed = True
    while changed:
        changed = False
        for name in sorted(installed):
            if not installed[name] and not needed_by(name):
                remove(name)
                changed = True


for command, arg in [("install", "app"), ("install", "cli"), ("remove", "log"),
                     ("remove", "app"), ("autoremove", None), ("list", None)]:
    print("$", command if arg is None else command + " " + arg)
    if command == "install":
        install(arg)
    elif command == "remove":
        remove(arg)
    elif command == "autoremove":
        autoremove()
    else:
        for name in sorted(installed):
            print(" ", name, "(asked)" if installed[name] else "(dependency)")
Output
$ install app
  install http (dependency)
  install log (dependency)
  install web (dependency)
  install app (asked)
$ install cli
  install cli (asked)
$ remove log
  error: log is needed by app, cli, web
$ remove app
  remove app
$ autoremove
  remove web
  remove http
$ list
  cli (asked)
  log (dependency)
  • Verdict: idiom. A dict maps each package to its dependencies, and a second dict maps each installed package to its flag.
  • install is recursive, so the dependencies are installed before the package. A package that is already installed returns at once, so log is installed one time.
  • autoremove loops until a pass removes nothing, because removing web makes http unused.
JavaGitHub
// A tiny package manager: install with dependencies, refuse to break them, and remove unused ones.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    static final Map<String, List<String>> REGISTRY = Map.of(
            "app", List.of("web", "log"),
            "web", List.of("http", "log"),
            "http", List.of(),
            "log", List.of(),
            "cli", List.of("log"));

    // A name maps to true if the user asked for it, false if it came as a dependency.
    static final TreeMap<String, Boolean> installed = new TreeMap<>();

    static String label(boolean asked) {
        return asked ? "(asked)" : "(dependency)";
    }

    static void install(String name, boolean asked) {
        if (installed.containsKey(name)) {
            installed.put(name, installed.get(name) || asked);
            return;
        }
        for (String dep : REGISTRY.get(name)) {
            install(dep, false);
        }
        installed.put(name, asked);
        System.out.println("  install " + name + " " + label(asked));
    }

    static List<String> neededBy(String name) {
        List<String> users = new ArrayList<>();
        for (String p : installed.keySet()) {
            if (REGISTRY.get(p).contains(name)) {
                users.add(p);
            }
        }
        return users;
    }

    static void remove(String name) {
        List<String> users = neededBy(name);
        if (!users.isEmpty()) {
            System.out.println("  error: " + name + " is needed by " + String.join(", ", users));
            return;
        }
        installed.remove(name);
        System.out.println("  remove " + name);
    }

    static void autoremove() {
        boolean changed = true;
        while (changed) {
            changed = false;
            for (String name : new ArrayList<>(installed.keySet())) {
                if (installed.containsKey(name) && !installed.get(name) && neededBy(name).isEmpty()) {
                    remove(name);
                    changed = true;
                }
            }
        }
    }

    public static void main(String[] args) {
        String[][] steps = {{"install", "app"}, {"install", "cli"}, {"remove", "log"},
                {"remove", "app"}, {"autoremove", ""}, {"list", ""}};
        for (String[] s : steps) {
            System.out.println(("$ " + s[0] + " " + s[1]).strip());
            switch (s[0]) {
                case "install" -> install(s[1], true);
                case "remove" -> remove(s[1]);
                case "autoremove" -> autoremove();
                default -> installed.forEach((name, asked) ->
                        System.out.println("  " + name + " " + label(asked)));
            }
        }
    }
}
Output
$ install app
  install http (dependency)
  install log (dependency)
  install web (dependency)
  install app (asked)
$ install cli
  install cli (asked)
$ remove log
  error: log is needed by app, cli, web
$ remove app
  remove app
$ autoremove
  remove web
  remove http
$ list
  cli (asked)
  log (dependency)
  • Verdict: idiom. Map.of holds the registry, which does not change, and a TreeMap holds the installed packages in name order.
  • autoremove loops over a copy of the keys, because remove changes the map during the loop.
  • A switch with arrows runs one command for each step.
// A tiny package manager: install with dependencies, refuse to break them, and remove unused ones.
var registry = new Dictionary<string, string[]>
{
    ["app"] = ["web", "log"],
    ["web"] = ["http", "log"],
    ["http"] = [],
    ["log"] = [],
    ["cli"] = ["log"],
};

// A name maps to true if the user asked for it, false if it came as a dependency.
var installed = new SortedDictionary<string, bool>(StringComparer.Ordinal);

string Label(bool asked) => asked ? "(asked)" : "(dependency)";

void Install(string name, bool asked)
{
    if (installed.TryGetValue(name, out bool was))
    {
        installed[name] = was || asked;
        return;
    }
    foreach (string dep in registry[name])
    {
        Install(dep, false);
    }
    installed[name] = asked;
    Console.WriteLine($"  install {name} {Label(asked)}");
}

List<string> NeededBy(string name) =>
    installed.Keys.Where(p => registry[p].Contains(name)).ToList();

void Remove(string name)
{
    var users = NeededBy(name);
    if (users.Count > 0)
    {
        Console.WriteLine($"  error: {name} is needed by {string.Join(", ", users)}");
        return;
    }
    installed.Remove(name);
    Console.WriteLine($"  remove {name}");
}

void Autoremove()
{
    bool changed = true;
    while (changed)
    {
        changed = false;
        foreach (string name in installed.Keys.ToList())
        {
            if (installed.TryGetValue(name, out bool asked) && !asked && NeededBy(name).Count == 0)
            {
                Remove(name);
                changed = true;
            }
        }
    }
}

(string Command, string Arg)[] steps =
[
    ("install", "app"), ("install", "cli"), ("remove", "log"),
    ("remove", "app"), ("autoremove", ""), ("list", ""),
];
foreach (var (command, arg) in steps)
{
    Console.WriteLine($"$ {command} {arg}".TrimEnd());
    switch (command)
    {
        case "install": Install(arg, true); break;
        case "remove": Remove(arg); break;
        case "autoremove": Autoremove(); break;
        default:
            foreach (var (name, asked) in installed)
            {
                Console.WriteLine($"  {name} {Label(asked)}");
            }
            break;
    }
}
Output
$ install app
  install http (dependency)
  install log (dependency)
  install web (dependency)
  install app (asked)
$ install cli
  install cli (asked)
$ remove log
  error: log is needed by app, cli, web
$ remove app
  remove app
$ autoremove
  remove web
  remove http
$ list
  cli (asked)
  log (dependency)
  • Verdict: idiom. A Dictionary holds the registry, and a SortedDictionary with an ordinal comparer holds the installed packages in name order.
  • autoremove loops over installed.Keys.ToList(), a copy, because Remove changes the dictionary during the loop.
  • Local functions in the top-level program share the two dictionaries.
// A tiny package manager: install with dependencies, refuse to break them, and remove unused ones.
package main

import (
	"fmt"
	"slices"
	"sort"
	"strings"
)

var registry = map[string][]string{
	"app":  {"web", "log"},
	"web":  {"http", "log"},
	"http": {},
	"log":  {},
	"cli":  {"log"},
}

// installed maps a name to true if the user asked for it, false if it came as a dependency.
var installed = map[string]bool{}

func names() []string {
	var list []string
	for name := range installed {
		list = append(list, name)
	}
	sort.Strings(list)
	return list
}

func install(name string, asked bool) {
	if was, ok := installed[name]; ok {
		installed[name] = was || asked
		return
	}
	for _, dep := range registry[name] {
		install(dep, false)
	}
	installed[name] = asked
	fmt.Println("  install", name, label(asked))
}

func label(asked bool) string {
	if asked {
		return "(asked)"
	}
	return "(dependency)"
}

func neededBy(name string) []string {
	var users []string
	for _, p := range names() {
		if slices.Contains(registry[p], name) {
			users = append(users, p)
		}
	}
	return users
}

func remove(name string) {
	if users := neededBy(name); len(users) > 0 {
		fmt.Println("  error:", name, "is needed by", strings.Join(users, ", "))
		return
	}
	delete(installed, name)
	fmt.Println("  remove", name)
}

func autoremove() {
	for changed := true; changed; {
		changed = false
		for _, name := range names() {
			if _, ok := installed[name]; ok && !installed[name] && len(neededBy(name)) == 0 {
				remove(name)
				changed = true
			}
		}
	}
}

func main() {
	steps := [][2]string{{"install", "app"}, {"install", "cli"}, {"remove", "log"},
		{"remove", "app"}, {"autoremove", ""}, {"list", ""}}
	for _, s := range steps {
		fmt.Println(strings.TrimSpace("$ " + s[0] + " " + s[1]))
		switch s[0] {
		case "install":
			install(s[1], true)
		case "remove":
			remove(s[1])
		case "autoremove":
			autoremove()
		default:
			for _, name := range names() {
				fmt.Println(" ", name, label(installed[name]))
			}
		}
	}
}
Output
$ install app
  install http (dependency)
  install log (dependency)
  install web (dependency)
  install app (asked)
$ install cli
  install cli (asked)
$ remove log
  error: log is needed by app, cli, web
$ remove app
  remove app
$ autoremove
  remove web
  remove http
$ list
  cli (asked)
  log (dependency)
  • Verdict: idiom. A map[string][]string is the registry, and a map[string]bool holds the installed packages.
  • Go does not keep the order of a map, so names sorts the keys before each loop. Without the sort, the output order changes from run to run.
  • slices.Contains checks whether a package lists a dependency.
  • Project and global installs. A language package manager usually installs into one project, for example into the folder node_modules of a Node.js project, so that two projects can use different versions of a library. A system package manager installs into shared directories for all users.72
  • One version or many. apt installs one version of each package on the system. npm can install two versions of a package in nested node_modules folders when two packages need versions that are not compatible.7 See Transitive dependencies.
  • Purely functional deployment. Nix stores each package in a path that depends on all the inputs that built it. In Dolstra's words, "a binary component is uniquely defined by the declared inputs used to build the component", so many versions can be installed side by side, and an upgrade does not overwrite a package that another program uses.8
  • Minimal versions. Go modules do not pick the newest version in the registry. Each module gives only a minimum version for each requirement, and the build uses the highest of these minimums. Cox calls this minimal version selection.9
  • Build tools with a package manager. Cargo also builds the code: it fetches and builds the dependencies, and it calls rustc with the correct parameters.1

Pitfalls

  • Breaking a shared dependency. If an upgrade replaces a library that another program needs, the other program can fail. Dolstra describes this as "the well-known DLL hell, where upgrading or installing one application can cause a failure in another application due to shared dynamic libraries".8 Use the package manager, not manual copies, so that it can check the dependencies.
  • Removing too much. apt autoremove removes the packages that are marked as automatic. The apt manual asks you to check that the list does not include applications that you use, even if they were once installed only as a dependency, and to mark such a package as manually installed.5
  • Mixing package managers. If pip and the system package manager both install packages into the same Python installation, they can conflict. The Python packaging specification for externally managed environments says that this can "break the entire underlying operating system at worst". When an installation has this marker file, an installer such as pip should refuse to install outside a virtual environment, and it can offer an override such as --break-system-packages.10 Install language packages into a project or a virtual environment.
  • Unpinned versions. Without a lock file, the same command can install other versions next week. See Lock files.

Cost

A package manager saves the work of finding, downloading and checking each dependency by hand. The costs are these:

  • Resolution time. Because dependency solving is NP-complete in general, a solver can take a long time on a large set of constraints, or fail to find a solution that exists.6
  • Disk space. Project installs and side-by-side versions keep many copies of the same library. Nix keeps the versions side by side, and it has automatic garbage collection of unused components.8
  • Trust. Each dependency is code from another person that runs in your build or your program.

History

CPAN, the archive of Perl modules, "has been online since October 1995".11 Debian uses dpkg and apt, with a model of packages that declare their dependencies and conflicts.2 Language package managers such as pip, npm and Cargo followed for most languages.341 In 2006 Eelco Dolstra described the purely functional deployment model of Nix in a PhD thesis at Utrecht University.8 In 2018 Russ Cox proposed minimal version selection for Go.9 In 2020 Abate and others looked back at the research on dependency solving, and found that some proposals, such as SAT-based dependency solving, were starting to take off in package managers.6

References

  1. The Cargo Book, Why Cargo Exists, Preliminaries; Enter Cargo
  2. The Debian GNU/Linux FAQ, Chapter 7, Basics of the Debian package management system, 7.1 What is a Debian package; 7.9 Depends, Recommends, Suggests, Conflicts, Replaces, Breaks or Provides
  3. pip documentation, the first paragraph
  4. npm Docs, About npm, the first paragraphs; Use npm to
  5. Debian trixie manual pages, apt(8), DESCRIPTION; update; install; remove; autoremove
  6. Pietro Abate, Roberto Di Cosmo, Georgios Gousios and Stefano Zacchiroli, Dependency Solving Is Still Hard, but We Are Getting Better at It, SANER 2020, abstract
  7. npm Docs (v11), folders, Cycles, Conflicts, and Folder Parsimony
  8. Eelco Dolstra, The Purely Functional Software Deployment Model, PhD thesis, Utrecht University, 2006, title page; 1.5 Contributions; the discussion of DLL hell in chapter 1
  9. Russ Cox, Minimal Version Selection (Go and Versioning, Part 4), 2018, the introduction
  10. Python Packaging User Guide, Externally Managed Environments, the introduction; Overview
  11. The Comprehensive Perl Archive Network (CPAN), Welcome to CPAN

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/3M0H3Z/text.yaml