Skip to content

Instantly share code, notes, and snippets.

@JeffreyVdb
Last active December 29, 2021 19:45
Show Gist options
  • Save JeffreyVdb/e5632fb53f3cc512e19afe980add0c11 to your computer and use it in GitHub Desktop.
Save JeffreyVdb/e5632fb53f3cc512e19afe980add0c11 to your computer and use it in GitHub Desktop.
Build PATH variable via checking if the provided arguments are existing directories
import sys
import os.path
if __name__ == "__main__":
paths = [p for p in sys.argv[1:] if os.path.exists(p) and os.path.isdir(p)]
if not paths:
sys.exit(0)
print(os.path.pathsep.join(paths))
const std = @import("std");
const builtin = @import("builtin");
const os = std.os;
const fs = std.fs;
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const stdout = std.io.getStdOut().writer();
const args = try std.process.argsAlloc(allocator);
var qualifiers = LinkedList([:0]const u8).init(allocator);
var path_length = @as(usize, 0);
for (args[1..]) |arg| {
var d = fs.cwd().openDir(arg, .{}) catch |err| switch (err) {
error.FileNotFound, error.NotDir => continue,
else => return err,
};
d.close();
path_length += arg.len;
try qualifiers.push(arg);
}
if (qualifiers.len == 0) return;
var qualifiers_iter = qualifiers.iterator();
var print_buf = try allocator.alloc(u8, path_length + qualifiers.len);
var current_offset = @as(usize, 0);
while (qualifiers_iter.next()) |v| {
const dest = print_buf[current_offset..];
std.mem.copy(u8, dest, v);
dest[v.len] = fs.path.delimiter;
current_offset += v.len + 1;
}
try stdout.print("{s}\n", .{print_buf[0 .. current_offset - 1]});
}
fn LinkedList(comptime T: type) type {
return struct {
const This = @This();
const Node = struct {
data: T,
next: ?*Node,
};
const Iterator = struct {
const It = @This();
current: ?*Node,
pub fn next(this: *It) ?T {
const cur_val = this.current orelse return null;
defer this.current = cur_val.next;
return cur_val.data;
}
};
allocator: std.mem.Allocator,
start: ?*Node,
end: ?*Node,
len: usize,
pub fn init(allocator: std.mem.Allocator) This {
return This{
.allocator = allocator,
.start = null,
.end = null,
.len = 0,
};
}
pub fn iterator(this: *This) Iterator {
return Iterator{ .current = this.start };
}
pub fn push(this: *This, value: T) !void {
const node = try this.allocator.create(Node);
node.* = .{ .data = value, .next = null };
if (this.end) |end| end.next = node else this.start = node;
this.end = node;
this.len += 1;
}
pub fn popStart(this: *This) ?T {
const start = this.start orelse return null;
defer {
this.len -= 1;
this.allocator.destroy(start);
}
if (start.next) |next| {
this.start = next;
} else {
this.start = null;
this.end = null;
}
return start.data;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment