Last active
October 22, 2021 12:28
-
-
Save JeffreyVdb/291c115020775900e35950d12082c585 to your computer and use it in GitHub Desktop.
Change owner of a file / directory using zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const c = @cImport(@cInclude("unistd.h")); | |
const std = @import("std"); | |
const ChownData = struct { | |
uid: c_uint, | |
gid: c_uint, | |
filename: [:0]const u8, | |
}; | |
pub fn main() !void { | |
const stdout = std.io.getStdOut().writer(); | |
const stderr = std.io.getStdErr().writer(); | |
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); | |
defer arena.deinit(); | |
const allocator = &arena.allocator; | |
const args = try std.process.argsAlloc(allocator); | |
defer std.process.argsFree(allocator, args); | |
if (args.len != 3) { | |
try stderr.print("Expected 2 arguments\n", .{}); | |
std.os.exit(1); | |
} | |
const payload = try parseArgs(args[1], args[2]); | |
try stdout.print("Changing to user {d} and gid {d} on file {s}\n", .{ payload.uid, payload.gid, payload.filename } | |
); | |
const result = c.chown(payload.filename, payload.uid, payload.gid); | |
if (result == -1) { | |
const err_str = switch (std.os.errno(result)) { | |
1 => "permission denied", | |
2 => "no such file or directory", | |
else => "something I don't know", | |
}; | |
try stderr.print("Somethin went wrong while changing permissions on file {s} ({s})\n", .{ payload.filename, er | |
r_str }); | |
std.os.exit(1); | |
} | |
} | |
fn parseArgs(user_gid: [:0]const u8, filename: [:0]const u8) !ChownData { | |
const delim_u8 = [_]u8{std.fs.path.delimiter}; | |
var it = std.mem.split(user_gid, delim_u8[0..]); | |
var uid: c_uint = undefined; | |
var gid: c_uint = undefined; | |
if (it.next()) |uidU8| uid = try std.fmt.parseInt(c_uint, uidU8, 10); | |
if (it.next()) |gidU8| gid = try std.fmt.parseInt(c_uint, gidU8, 10); | |
return ChownData{ .uid = uid, .gid = gid, .filename = filename }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment