13 Commits

Author SHA1 Message Date
76cb69f0a5 Add basic ~ support 2025-03-31 08:31:14 -04:00
a458e4f55c Add author builtin 2025-03-31 07:59:01 -04:00
8b459cb7cb this is reeeeaaal goooood 2025-03-31 07:58:56 -04:00
8e63cd206f add STUPID nomorenumbers impl 2025-03-30 17:52:50 -04:00
ae43f4afbf Added exit builtin 2025-03-30 17:45:24 -04:00
425f5ab3bf MVP working 2025-03-30 16:06:42 -04:00
767881893a 2025-03-30 14:58:28 -04:00
74b2566cb4 2025-03-30 14:58:15 -04:00
1584eaee8e 2025-03-30 12:53:07 -04:00
37166d75d5 2025-03-30 12:23:43 -04:00
1ba8312703 2025-03-30 09:10:18 -04:00
95c5a9cccc Trying to get prompt 2025-03-25 21:49:32 -04:00
c46c50737f Reading input in zig
using a readline style library too.
2025-03-25 20:15:44 -04:00
7 changed files with 465 additions and 10 deletions

2
.gitignore vendored
View File

@@ -1,2 +1,4 @@
*.out
bin/
.zig-cache
zig-out

View File

@@ -1,18 +1,15 @@
LIBRARIES = -lreadline
RELEASE_ARGS = -DRELEASEBUILD
SOURCES = ./msh.c
OUTPUT_DIR = ./bin
OUTPUT_DIR = ./zig-out/bin
OUTPUT_BIN = ${OUTPUT_DIR}/PROG
OUTPUT = -o ${OUTPUT_BIN}
build: output_dir
gcc -Wall -std=gnu99 ${RELEASE_ARGS} ${SOURCES} ${OUTPUT:PROG=mash} ${LIBRARIES}
zig build install --release=fast
debug: output_dir
gcc -Wall -std=gnu99 -g ${SOURCES} ${OUTPUT:PROG=mash} ${LIBRARIES}
output_dir:
mkdir -p ${OUTPUT_DIR}
zig build
install:
mv ${OUTPUT_BIN:PROG=mash} /usr/sbin/blah

81
build.zig Normal file
View File

@@ -0,0 +1,81 @@
const std = @import("std");
// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
const linenoise = b.dependency("linenoize", .{
.target = target,
.optimize = optimize,
}).module("linenoise");
// We will also create a module for our other entry point, 'main.zig'.
const exe_mod = b.createModule(.{
// `root_source_file` is the Zig "entry point" of the module. If a module
// only contains e.g. external object files, you can make this `null`.
// In this case the main source file is merely a path, however, in more
// complicated build scripts, this could be a generated file.
.root_source_file = b.path("src/main.zig"),
.imports = &.{.{ .name = "linenoise", .module = linenoise }},
.target = target,
.optimize = optimize,
});
// This creates another `std.Build.Step.Compile`, but this one builds an executable
// rather than a static library.
const exe = b.addExecutable(.{
.name = "math_shell",
.root_module = exe_mod,
});
// This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default
// step when running `zig build`).
b.installArtifact(exe);
// This *creates* a Run step in the build graph, to be executed when another
// step is evaluated that depends on it. The next line below will establish
// such a dependency.
const run_cmd = b.addRunArtifact(exe);
// By making the run step depend on the install step, it will be run from the
// installation directory rather than directly from within the cache directory.
// This is not necessary, however, if the application depends on other installed
// files, this ensures they will be present and in the expected location.
run_cmd.step.dependOn(b.getInstallStep());
// This allows the user to pass arguments to the application in the build
// command itself, like this: `zig build run -- arg1 arg2 etc`
if (b.args) |args| {
run_cmd.addArgs(args);
}
// This creates a build step. It will be visible in the `zig build --help` menu,
// and can be selected like this: `zig build run`
// This will evaluate the `run` step rather than the default, which is "install".
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const exe_unit_tests = b.addTest(.{
.root_module = exe_mod,
});
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
// Similar to creating the run step earlier, this exposes a `test` step to
// the `zig build --help` menu, providing a way for the user to request
// running the unit tests.
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_exe_unit_tests.step);
}

52
build.zig.zon Normal file
View File

@@ -0,0 +1,52 @@
.{
// This is the default name used by packages depending on this one. For
// example, when a user runs `zig fetch --save <url>`, this field is used
// as the key in the `dependencies` table. Although the user can choose a
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = .math_shell,
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// Together with name, this represents a globally unique package
// identifier. This field is generated by the Zig toolchain when the
// package is first created, and then *never changes*. This allows
// unambiguous detection of one package being an updated version of
// another.
//
// When forking a Zig project, this id should be regenerated (delete the
// field and run `zig build`) if the upstream project is still maintained.
// Otherwise, the fork is *hostile*, attempting to take control over the
// original project's identity. Thus it is recommended to leave the comment
// on the following line intact, so that it shows up in code reviews that
// modify the field.
.fingerprint = 0x62a0107bbe8924ff, // Changing this has security and trust implications.
// Tracks the earliest Zig version that the package considers to be a
// supported use case.
.minimum_zig_version = "0.14.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
.linenoize = .{
.url = "git+https://github.com/joachimschmidt557/linenoize?ref=v0.1.0#8bf767663382624bd676b05829fa8d3975a05d88",
.hash = "linenoize-0.1.0-J7HK8IfXAABxH-V4Bp2Q0G7P-nrOmq9g8LuQAoX3SjDy",
},
},
.paths = .{
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
//"README.md",
},
}

4
msh.h
View File

@@ -1,4 +0,0 @@
int builtinExit(char **args);
int builtinAuthor(char **args);
int builtinCD(char **dir);
int builtinNMN(char **args);

7
src/get_prompt.bash Normal file
View File

@@ -0,0 +1,7 @@
ver=$(bash --version | head -n 1 | awk '{print $4}' | grep -o "\.\..")
check_ver=$(echo -e "${ver}\n4.3" | sort -V | head -n 1)
if [[ "${ver}" == "${check_ver}" ]]; then
echo -n "[${USER}@${HOSTNAME} ${PWD##*/}]$ "
else
echo -n "${PS1@P}"
fi

320
src/main.zig Normal file
View File

@@ -0,0 +1,320 @@
pub fn main() !void {
clear();
var gpa = std.heap.GeneralPurposeAllocator(.{}).init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var ln = Linenoise.init(allocator);
defer ln.deinit();
var prng = Random.DefaultPrng.init(blk: {
var seed: u64 = undefined;
try posix.getrandom(mem.asBytes(&seed));
break :blk seed;
});
const rand = prng.random();
const uname_cmd = try tokenizeCommand("uname -a", allocator);
defer allocator.free(uname_cmd);
var shell_state: ShellState = .{
.env_map = try process.getEnvMap(allocator),
};
defer shell_state.env_map.deinit();
_ = try runCommand(uname_cmd, &shell_state, allocator);
var p = try getPrompt(allocator);
var limit: i32 = 100;
while (try ln.linenoise(p)) |input| {
allocator.free(p);
defer allocator.free(input);
if (input.len > 0) {
try ln.history.add(input);
const command = try tokenizeCommand(input, allocator);
defer allocator.free(command);
if (!shell_state.should_test or
eql(u8, command[0], "nomorenumbers") or
try mathTest(rand, limit, shell_state.iteration))
{
_ = execCommand(command, &shell_state, allocator) catch |err| switch (err) {
error.FileNotFound => print("mash: {s}: command not found\n", .{command[0]}),
error.AccessDenied => print("mash: {s}: Permission denied\n", .{command[0]}),
else => print("Unkown error: {}\n", .{err}),
};
} else {
print(
\\
\\How can you expect to execute commands without knowing any math???
\\
, .{});
}
shell_state.iteration += 1;
if (shell_state.iteration % 3 == 0) {
limit *= 10;
}
}
if (shell_state.should_exit) break;
p = try getPrompt(allocator);
} else allocator.free(p); // free on crtl+d
}
const ShellState = struct {
iteration: u32 = 0,
should_test: bool = true,
should_exit: bool = false,
env_map: process.EnvMap,
};
const Operator = enum(u8) {
add = 0,
subtract,
multiply,
divide,
const Self = @This();
fn toString(s: Self) []const u8 {
return switch (s) {
.add => "+",
.subtract => "-",
.multiply => "*",
.divide => "/",
};
}
fn apply(s: Self, a: i32, b: i32) i32 {
return switch (s) {
.add => a + b,
.subtract => a - b,
.multiply => a * b,
.divide => @divTrunc(a, b),
};
}
/// Gets add or subtract for the first three commands.
/// Includes multiplication and division after the first three.
fn rand(r: Random, iteration: u32) Self {
if (iteration > 3) {
return r.enumValue(Self);
} else {
return @enumFromInt(r.uintAtMost(u8, 1));
}
}
};
/// return true if the user passed, false if the user did not.
fn mathTest(rand: Random, limit: i32, iteration: u32) !bool {
const op = Operator.rand(rand, iteration);
const num1 = rand.intRangeAtMost(i32, 1, limit);
const num2 = rand.intRangeAtMost(i32, 1, limit);
const answer = op.apply(num1, num2);
if (comptime builtin.mode == .Debug) {
print("Answer: {d}\n", .{answer});
}
print("{d} {s} {d} = ", .{ num1, op.toString(), num2 });
defer {
print("Calculating", .{});
for (0..3) |_| {
print(".", .{});
if (comptime builtin.mode != .Debug) {
sleep(2 * 1000 * 1000 * 1000);
}
}
print("\n", .{});
}
return answer == while (true) {
break readInt(stdin) catch |err| switch (err) {
error.InvalidCharacter, error.EndOfStream => continue,
else => return err,
};
};
}
const BuiltinFunc = *const fn (*ShellState, [][]const u8, Allocator) anyerror!void;
fn exitFn(shell_state: *ShellState, command: [][]const u8, allocator: Allocator) !void {
_ = command;
_ = allocator;
shell_state.*.should_exit = true;
}
fn nomorenumbersFn(shell_state: *ShellState, command: [][]const u8, allocator: Allocator) !void {
shell_state.*.should_test = false;
if (command.len > 1) {
_ = execCommand(command[1..], shell_state, allocator) catch |err| {
return err;
};
}
}
fn cdFn(shell_state: *ShellState, command: [][]const u8, allocator: Allocator) !void {
const cwd = fs.cwd();
var env_map = shell_state.*.env_map;
const pwd = try cwd.realpathAlloc(allocator, ".");
const old_pwd = env_map.get("OLDPWD");
const home = env_map.get("HOME");
defer allocator.free(pwd);
var buf: [fs.max_path_bytes]u8 = undefined;
var err: ?anyerror = null;
var target: ?[]const u8 = null;
if (command.len == 1) {
if (home) |h| {
target = h;
}
} else if (command[1][0] == '~') {
if (home) |h| {
const numReplacements = mem.replace(u8, command[1], "~", h, &buf);
const len = command[1].len - numReplacements + (numReplacements * h.len);
target = buf[0..len];
}
} else if (eql(u8, command[1], "-")) {
if (old_pwd) |old| {
target = old;
} else {
print("mash: cd: OLDPWD not set\n", .{});
return;
}
} else {
target = cwd.realpath(command[1], &buf) catch |e| blk: {
err = e;
break :blk null;
};
}
if (target) |t| {
if (posix.chdir(t)) {
try env_map.put("OLDPWD", pwd);
try env_map.put("PWD", t);
} else |e| {
err = e;
}
}
if (err) |e| {
switch (e) {
error.FileNotFound => {
print("mash: cd: {s}: No such file or directory\n", .{target orelse command[1]});
return;
},
error.AccessDenied => {
print("mash: cd: {s}: Permission denied\n", .{target orelse command[1]});
return;
},
error.NameTooLong => {
print("mash: cd: {s}: File name too long\n", .{target orelse command[1]});
return;
},
else => return e,
}
}
}
fn authorFn(shell_state: *ShellState, command: [][]const u8, allocator: Allocator) !void {
_ = shell_state;
_ = command;
_ = allocator;
print(
\\Author: Robby
\\Description: A shell to promote math!
\\Ask for the source code!
\\
\\Derived from an earlier version written in C by Spencer.
\\
, .{});
}
fn execCommand(command: [][]const u8, shell_state: *ShellState, allocator: Allocator) !u8 {
const builtins = comptime .{
.{ "exit", exitFn },
.{ "nomorenumbers", nomorenumbersFn },
.{ "cd", cdFn },
.{ "author", authorFn },
};
const builtinMap = StaticStringMap(BuiltinFunc).initComptime(builtins);
if (builtinMap.has(command[0])) {
try builtinMap.get(command[0]).?(shell_state, command, allocator);
return 0;
} else {
return runCommand(command, shell_state, allocator);
}
}
fn runCommand(command: [][]const u8, shell_state: *ShellState, allocator: Allocator) !u8 {
var child = process.Child.init(command, allocator);
child.env_map = &shell_state.env_map;
const result = try child.spawnAndWait();
return result.Exited;
}
fn getPrompt(allocator: Allocator) ![]const u8 {
const script = @embedFile("./get_prompt.bash");
const result = try process.Child.run(.{
.allocator = allocator,
.argv = &[_][]const u8{ "bash", "-i", "-c", script },
});
allocator.free(result.stderr);
return result.stdout;
}
fn tokenizeCommand(command: []const u8, allocator: Allocator) ![][]const u8 {
var argv_array_list = ArrayList([]const u8).init(allocator);
defer argv_array_list.deinit();
var tokens = tokenizeAny(u8, command, "\t\r\n ");
while (tokens.next()) |token| {
try argv_array_list.append(token);
}
return argv_array_list.toOwnedSlice();
}
fn clear() void {
print("\u{001b}[H\u{001b}[J", .{});
}
fn print(comptime fmt: []const u8, args: anytype) void {
stdout.print(fmt, args) catch unreachable;
}
fn readInt(reader: anytype) !i32 {
var buf: [1024]u8 = undefined;
const buf2 = try reader.readUntilDelimiter(&buf, '\n');
return std.fmt.parseInt(i32, buf2, 0);
}
const std = @import("std");
const posix = std.posix;
const fs = std.fs;
const path = std.fs.path;
const mem = std.mem;
const Allocator = mem.Allocator;
const eql = mem.eql;
const Reader = std.io.Reader;
const stdout = std.io.getStdOut().writer();
const stdin = std.io.getStdIn().reader();
const tokenizeAny = mem.tokenizeAny;
const process = std.process;
const sleep = std.Thread.sleep;
const Random = std.Random;
const ArrayList = std.ArrayList;
const StaticStringMap = std.static_string_map.StaticStringMap;
const Linenoise = @import("linenoise").Linenoise;
const builtin = @import("builtin");