TExcelTAD
Home › C/C++ Packages: Conan 2, vcpkg & CPM.cmake › Package Management Exercises

Package Management Exercises

Each exercise is a small piece of the logic package managers run every day, written as a pure function with the tests already in place. Run the starter first: it prints wrong answers (None, empty lists), which shows what the tests expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real Conan session to fix.

Exercise 1: Parse a Conan reference

Topics: Conan 2: Install & First Look, Package IDs

Split a reference of the form name/version#rrev:package_id#prev into its parts. Everything after name/version is optional; missing parts are None.

python · try it yourself
def parse_ref(ref):
    # TODO: split on ":" (package part), then "#" (revisions), then "/" (name/version)
    return {"name": None, "version": None, "rrev": None, "package_id": None, "prev": None}

print(parse_ref("fmt/12.1.0"))
print(parse_ref("fmt/12.1.0#6baf0fb8"))
print(parse_ref("spdlog/1.17.0#bcbaaf71:68cf2b88#81ce70d6"))
{'name': None, 'version': None, 'rrev': None, 'package_id': None, 'prev': None}
{'name': None, 'version': None, 'rrev': None, 'package_id': None, 'prev': None}
{'name': None, 'version': None, 'rrev': None, 'package_id': None, 'prev': None}

Expected output:

text
{'name': 'fmt', 'version': '12.1.0', 'rrev': None, 'package_id': None, 'prev': None}
{'name': 'fmt', 'version': '12.1.0', 'rrev': '6baf0fb8', 'package_id': None, 'prev': None}
{'name': 'spdlog', 'version': '1.17.0', 'rrev': 'bcbaaf71', 'package_id': '68cf2b88', 'prev': '81ce70d6'}
Show solution
python
def parse_ref(ref):
    head, _, pkg = ref.partition(":")
    recipe, _, rrev = head.partition("#")
    name, _, version = recipe.partition("/")
    pid, _, prev = pkg.partition("#")
    return {"name": name, "version": version, "rrev": rrev or None,
            "package_id": pid or None, "prev": prev or None}

Exercise 2: Resolve a version range

Topics: Version Ranges & Conflicts

best(versions, rng) returns the newest version that satisfies every condition in rng (space-separated >=x, <x and ~x, where ~1.9 means "1.9.x"), or None. Compare versions as numbers: 1.10.1 is newer than 1.9.3.

python · try it yourself
def ver(s):
    return tuple(int(x) for x in s.split("."))

def satisfies(version, rng):
    # TODO: check every condition in rng.split()
    return False

def best(versions, rng):
    ok = [v for v in versions if satisfies(v, rng)]
    return max(ok, key=ver) if ok else None

vs = ["1.2.0", "1.9.3", "1.10.1", "2.0.0", "2.1.0"]
print(best(vs, ">=1.2 <2"))
print(best(vs, "~1.9"))
print(best(vs, ">=2.0.1"))
print(best(vs, ">=3"))
None
None
None
None

Expected output:

text
1.10.1
1.9.3
2.1.0
None
Show solution
python
def satisfies(version, rng):
    v = ver(version)
    for cond in rng.split():
        if cond.startswith(">="):
            if not v >= ver(cond[2:]): return False
        elif cond.startswith("<"):
            if not v < ver(cond[1:]): return False
        elif cond.startswith("~"):
            base = ver(cond[1:])
            if not (v >= base and v[:2] == base[:2]): return False
        else:
            raise ValueError(cond)
    return True

Exercise 3: vcpkg's version selection

Topics: Baselines, version>= & Overrides

Return the version vcpkg selects for one port: the override if there is one, otherwise the highest of the baseline and all version>= minimums. Versions may carry a port-version (1.3.1#2), which counts after the upstream version.

python · try it yourself
def ver(v):
    base, _, port = v.partition("#")
    return tuple(int(x) for x in base.split(".")) + (int(port or 0),)

def vcpkg_version(baseline, minimums, override=None):
    # TODO: override wins; otherwise the maximum of baseline and minimums
    return None

print(vcpkg_version("12.2.0#1", []))
print(vcpkg_version("11.2.0", ["11.0.2#1", "12.1.0"]))
print(vcpkg_version("1.3.1", ["1.3.1#2"]))
print(vcpkg_version("1.3.1", ["2.0.0"], override="1.2.13"))
None
None
None
None

Expected output:

text
12.2.0#1
12.1.0
1.3.1#2
1.2.13
Show solution
python
def vcpkg_version(baseline, minimums, override=None):
    if override is not None:
        return override
    return max([baseline] + minimums, key=ver)

Exercise 4: Build order by levels

Topics: The Dependency Graph

Given graph (package → list of dependencies), return the build levels: each level is the sorted list of packages whose dependencies are all in earlier levels. Raise ValueError("cycle: …") listing the remaining packages if no progress is possible.

python · try it yourself
def build_levels(graph):
    # TODO: repeatedly take every package whose dependencies are all done
    return []

print(build_levels({"app": ["spdlog", "zlib"], "spdlog": ["fmt"], "fmt": [], "zlib": []}))
print(build_levels({"a": ["b"], "b": ["c"], "c": []}))
try:
    build_levels({"a": ["b"], "b": ["a"], "c": []})
except ValueError as e:
    print(e)
[]
[]

Expected output:

text
[['fmt', 'zlib'], ['spdlog'], ['app']]
[['c'], ['b'], ['a']]
cycle: a, b
Show solution
python
def build_levels(graph):
    done, levels, todo = set(), [], set(graph)
    while todo:
        ready = sorted(n for n in todo if set(graph[n]) <= done)
        if not ready:
            raise ValueError("cycle: " + ", ".join(sorted(todo)))
        levels.append(ready)
        done |= set(ready)
        todo -= set(ready)
    return levels

Exercise 5: Review a lockfile update

Topics: Lockfiles, Field Notes: Pinning & Caching

A lockfile update pull request is easier to review as a summary. Given the old and new requires lists (entries like fmt/12.1.0#rrev), return sorted lines: + name version (added), - name version (removed) and ~ name old -> new (version changed). Ignore revisions.

python · try it yourself
def lock_diff(old, new):
    # TODO: map name -> version for both lists, then compare
    return []

old = ["spdlog/1.15.0#aaa", "fmt/11.1.0#bbb", "zlib/1.3.1#ccc"]
new = ["spdlog/1.17.0#ddd", "fmt/12.1.0#eee", "catch2/3.16.0#fff", "zlib/1.3.1#ccc"]
for line in lock_diff(old, new):
    print(line)
print(lock_diff(old, old))
[]

Expected output:

text
+ catch2 3.16.0
~ fmt 11.1.0 -> 12.1.0
~ spdlog 1.15.0 -> 1.17.0
[]
Show solution
python
def lock_diff(old, new):
    def table(entries):
        return {e.split("/")[0]: e.split("#")[0].split("/")[1] for e in entries}
    a, b = table(old), table(new)
    out = []
    for name in sorted(a.keys() | b.keys()):
        if name not in b:
            out.append(f"- {name} {a[name]}")
        elif name not in a:
            out.append(f"+ {name} {b[name]}")
        elif a[name] != b[name]:
            out.append(f"~ {name} {a[name]} -> {b[name]}")
    return out

Exercise 6: Fix the consumer

Topics: CMakeDeps, CMakeToolchain & Presets

This project configures fine but fails to compile. Read the error, then fix the one wrong line in CMakeLists.txt. The conan install output tells you the names to use.

bash · try it yourself
mkdir -p broken && cd broken
printf '[requires]\nspdlog/1.17.0\n[generators]\nCMakeDeps\nCMakeToolchain\n[layout]\ncmake_layout\n' > conanfile.txt
cat > CMakeLists.txt <<'TXT'
cmake_minimum_required(VERSION 3.25)
project(broken CXX)
find_package(spdlog REQUIRED CONFIG)
add_executable(app main.cpp)
target_link_libraries(app PRIVATE spdlog)
TXT
printf '#include <spdlog/spdlog.h>\nint main() { spdlog::set_pattern("%%v"); spdlog::info("fixed!"); }\n' > main.cpp
conan install . -c tools.build:jobs=1 2>&1 | grep -A2 'necessary find_package'
cmake --preset conan-release > /dev/null
cmake --build --preset conan-release 2>&1 | grep -E 'error|Error' | head -2
CMakeDeps necessary find_package() and targets for your CMakeLists.txt
    find_package(spdlog)
    target_link_libraries(... spdlog::spdlog)
/home/learner/broken/main.cpp:1:10: fatal error: spdlog/spdlog.h: No such file or directory
gmake[2]: *** [CMakeFiles/app.dir/build.make:79: CMakeFiles/app.dir/main.cpp.o] Error 1

Expected output once fixed (the last lines of the session, after building and running ./build/Release/app):

text
fixed!
Show solution

CMakeDeps printed the target to use: spdlog::spdlog.

cmake
target_link_libraries(app PRIVATE spdlog::spdlog)

Then cmake --build --preset conan-release && ./build/Release/app. The plain name spdlog isn't a target, so CMake treats it as a library file name (-lspdlog) and passes no include paths at all, which is why the compiler can't find spdlog/spdlog.h. Namespaced targets (pkg::target) make CMake fail loudly at configure time when the target doesn't exist, so always use them.

Test yourself

Why do the exercises compare versions as tuples of integers?

  1. It's faster
  2. As strings, "1.10.1" sorts before "1.9.3", which is wrong
  3. Python requires it
  4. To support Git hashes

In Exercise 3, why does 1.3.1#2 beat a 1.3.1 baseline?

  1. It's alphabetically later
  2. The port-version counts after the upstream version, so #2 is a newer packaging of the same release
  3. Minimums always win
  4. It doesn't