Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
cgbur committed Aug 13, 2023
1 parent c23598f commit 1c708f8
Show file tree
Hide file tree
Showing 5 changed files with 199 additions and 0 deletions.
16 changes: 16 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name: CI

on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: goto-bus-stop/setup-zig@v2
- run: zig build test
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: goto-bus-stop/setup-zig@v2
- run: zig fmt --check src/*.zig
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
zig-out/
zig-cache/
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# pc

A simple tool for quickly calculating the percentage change between a set of numbers.

## Usage

## Installation
72 changes: 72 additions & 0 deletions build.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
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 exe = b.addExecutable(.{
.name = "pc",
// 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 = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});

exe.strip = true;

// 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);

// Creates a step for unit testing. This only builds the test executable
// but does not run it.
const unit_tests = b.addTest(.{
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});

const run_unit_tests = b.addRunArtifact(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_unit_tests.step);
}
102 changes: 102 additions & 0 deletions src/main.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
const std = @import("std");
const ArrayList = std.ArrayList;

pub const EscapeCodes = struct {
pub const dim = "\x1b[2m";
pub const pink = "\x1b[38;5;205m";
pub const white = "\x1b[37m";
pub const red = "\x1b[31m";
pub const yellow = "\x1b[33m";
pub const green = "\x1b[32m";
pub const magenta = "\x1b[35m";
pub const cyan = "\x1b[36m";
pub const reset = "\x1b[0m";
pub const erase_line = "\x1b[2K\r";
};

const usage_text: []const u8 =
\\Usage: pc [numbers...] or ... | pc
\\Options:
\\ -h, --help: Show this help message
\\
;

fn parseNum(s: []const u8) ?f32 {
const val = std.fmt.parseFloat(f32, s) catch {
std.debug.print("skipping invalid number: '{s}'\n", .{s});
return null;
};
return val;
}

fn percentDiff(a: f32, b: f32) f32 {
return (b - a) / a * 100.0;
}

fn fancyPrint(writer: anytype, diff: f32) !void {
const symbol = blk: {
if (diff > 0.0) {
try writer.print("{s}", .{EscapeCodes.green});
break :blk "↑";
} else if (diff < 0.0) {
try writer.print("{s}", .{EscapeCodes.red});
break :blk "↓";
} else {
try writer.print("{s}", .{EscapeCodes.white});
break :blk "→";
}
};
try writer.print("{s} {d: >6.2}%\n", .{ symbol, diff });
}

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 nums = ArrayList(f32).init(allocator);
defer nums.deinit();

// parse args
var arg_i: usize = 1;
while (arg_i < args.len) : (arg_i += 1) {
const arg = args[arg_i];
if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) {
try stdout.writeAll(usage_text);
return std.process.cleanExit();
}
if (parseNum(arg)) |num| {
try nums.append(num);
}
}

// if no nums, read from stdin
if (nums.items.len == 0) {
var input = std.io.getStdIn().reader().readAllAlloc(allocator, 10 * 1024 * 1024) catch |e| {
std.debug.print("pc: error reading stdin: {s}\n", .{@errorName(e)});
return std.process.exit(1);
};
var it = std.mem.tokenizeAny(u8, input, " \t\n\r");
while (it.next()) |s| {
if (parseNum(s)) |num| {
try nums.append(num);
}
}
}

if (nums.items.len < 2) {
std.debug.print("pc: need at least 2 numbers\n", .{});
try stdout.writeAll(usage_text);
return std.process.exit(1);
}

// calculate percent difference between each pair
var cur = nums.items[0];
for (nums.items[1..]) |num| {
const diff = percentDiff(cur, num);
try fancyPrint(stdout, diff);
cur = num;
}
}

0 comments on commit 1c708f8

Please sign in to comment.