User.fromLine

This commit is contained in:
Motiejus Jakštys 2022-06-29 13:55:53 +03:00
parent 5d171883a7
commit e7fb0c18d4

View File

@ -48,44 +48,36 @@ pub fn clone(
// User.
fn fromLine(allocator: Allocator, err: *ErrCtx, line: []const u8) error{ InvalidRecord, OutOfMemory }!User {
var it = mem.split(u8, line, ":");
const name = it.next();
_ = it.next(); // password
const uids = it.next();
const gids = it.next();
const gecos = it.next();
const home = it.next();
const shell = it.next();
const name = it.next() orelse return err.returnf("too few fields", .{}, error.InvalidRecord);
_ = it.next() orelse return err.returnf("too few fields", .{}, error.InvalidRecord); // password
const uids = it.next() orelse return err.returnf("too few fields", .{}, error.InvalidRecord);
const gids = it.next() orelse return err.returnf("too few fields", .{}, error.InvalidRecord);
const gecos = it.next() orelse return err.returnf("too few fields", .{}, error.InvalidRecord);
const home = it.next() orelse return err.returnf("too few fields", .{}, error.InvalidRecord);
const shell = it.next() orelse return err.returnf("too few fields", .{}, error.InvalidRecord);
// all fields are set
if (shell == null)
return err.returnf("too few user fields in line: {s}", .{line}, error.InvalidRecord);
const uid = fmt.parseInt(u32, uids, 10) catch
return err.returnf("bad uid: {s}", .{uids}, error.InvalidRecord);
// the line must be exhaustive.
if (it.next() != null)
return error.returnf("too many fields in line", .{}, error.InvalidRecord);
const gid = fmt.parseInt(u32, gids, 10) catch
return err.returnf("bad gid: {s}", .{gids}, error.InvalidRecord);
const uid = fmt.parseInt(u32, uids.?, 10) catch
return err.returnf("bad uid: {s}", .{uids.?}, error.InvalidRecord);
const gid = fmt.parseInt(u32, gids.?, 10) catch
return err.returnf("bad uid: {s}", .{gids.?}, error.InvalidRecord);
validate.name(name.?, err) catch
return err.returnf("invalid name '{s}'", .{name.?}, error.InvalidRecord);
validate.gecos(gecos.?, err) catch
return err.returnf("invalid gecos '{s}'", .{gecos.?}, error.InvalidRecord);
validate.path(home.?, err) catch
return err.returnf("invalid home '{s}'", .{home.?}, error.InvalidRecord);
validate.path(shell.?, err) catch
return err.returnf("invalid shell '{s}'", .{shell.?}, error.InvalidRecord);
validate.name(name, err) catch
return err.returnf("invalid name '{s}'", .{name}, error.InvalidRecord);
validate.gecos(gecos, err) catch
return err.returnf("invalid gecos '{s}'", .{gecos}, error.InvalidRecord);
validate.path(home, err) catch
return err.returnf("invalid home '{s}'", .{home}, error.InvalidRecord);
validate.path(shell, err) catch
return err.returnf("invalid shell '{s}'", .{shell}, error.InvalidRecord);
const user = User{
.uid = uid,
.gid = gid,
.name = name.?,
.gecos = gecos.?,
.home = home.?,
.shell = shell.?,
.name = name,
.gecos = gecos,
.home = home,
.shell = shell,
};
return try user.clone(allocator);
}