aboutsummaryrefslogtreecommitdiff
path: root/src/Package.zig
blob: 03c9e9ea3d2b14f9bfa88430cbd492c3bc2dcb0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const Package = @This();

const std = @import("std");
const fs = std.fs;
const mem = std.mem;
const Allocator = mem.Allocator;

const Compilation = @import("Compilation.zig");

pub const Table = std.StringHashMapUnmanaged(*Package);

root_src_directory: Compilation.Directory,
/// Relative to `root_src_directory`. May contain path separators.
root_src_path: []const u8,
table: Table = .{},
parent: ?*Package = null,

/// Allocate a Package. No references to the slices passed are kept.
pub fn create(
    gpa: *Allocator,
    /// Null indicates the current working directory
    root_src_dir_path: ?[]const u8,
    /// Relative to root_src_dir_path
    root_src_path: []const u8,
) !*Package {
    const ptr = try gpa.create(Package);
    errdefer gpa.destroy(ptr);

    const owned_dir_path = if (root_src_dir_path) |p| try gpa.dupe(u8, p) else null;
    errdefer if (owned_dir_path) |p| gpa.free(p);

    const owned_src_path = try gpa.dupe(u8, root_src_path);
    errdefer gpa.free(owned_src_path);

    ptr.* = .{
        .root_src_directory = .{
            .path = owned_dir_path,
            .handle = if (owned_dir_path) |p| try fs.cwd().openDir(p, .{}) else fs.cwd(),
        },
        .root_src_path = owned_src_path,
    };

    return ptr;
}

/// Free all memory associated with this package and recursively call destroy
/// on all packages in its table
pub fn destroy(pkg: *Package, gpa: *Allocator) void {
    gpa.free(pkg.root_src_path);

    // If root_src_directory.path is null then the handle is the cwd()
    // which shouldn't be closed.
    if (pkg.root_src_directory.path) |p| {
        gpa.free(p);
        pkg.root_src_directory.handle.close();
    }

    {
        var it = pkg.table.iterator();
        while (it.next()) |kv| {
            if (pkg != kv.value) {
                kv.value.destroy(gpa);
            }
            gpa.free(kv.key);
        }
    }

    pkg.table.deinit(gpa);
    gpa.destroy(pkg);
}

pub fn add(pkg: *Package, gpa: *Allocator, name: []const u8, package: *Package) !void {
    try pkg.table.ensureCapacity(gpa, pkg.table.count() + 1);
    const name_dupe = try mem.dupe(gpa, u8, name);
    pkg.table.putAssumeCapacityNoClobber(name_dupe, package);
}