Compare commits

...

3 commits

2 changed files with 62 additions and 9 deletions

View file

@ -2,8 +2,34 @@ using System;
using System.IO; using System.IO;
using System.Security.Cryptography; using System.Security.Cryptography;
// get resource path from var or default
string resourcePath = Environment.GetEnvironmentVariable("FORTUNE_CS_DIR");
if(resourcePath == "" || !Directory.Exists(resourcePath))
resourcePath = "/usr/share/fortune-cs/";
// pull file arg if 1 argument is provided
string file = null;
if(args.Length == 1) {
file = args[0];
// if the file doens't exist, see if it's in `resourcePath`
if(!File.Exists(file)) {
if(!file.EndsWith(".txt"))
file = file + ".txt";
file = resourcePath + file;
if(!File.Exists(file)) {
// don't try to read a file that doesn't exist
Console.WriteLine($"fortune-cs: no file '{file}' found.");
return 2;
}
}
}
// run merge if more than 1 argument is provided
else if(args.Length > 0) {
Utilities.Merge(args);
return 0;
}
// make sure fortune directory exists // make sure fortune directory exists
var resourcePath = "/usr/share/fortune-cs/";
if(!Directory.Exists(resourcePath)) { if(!Directory.Exists(resourcePath)) {
Console.WriteLine("fortune-cs: directory '/usr/share/fortune-cs/' does not exist"); Console.WriteLine("fortune-cs: directory '/usr/share/fortune-cs/' does not exist");
return 1; return 1;
@ -12,19 +38,17 @@ if(!Directory.Exists(resourcePath)) {
// pull file list // pull file list
var files = Directory.GetFiles(resourcePath, "*.txt"); var files = Directory.GetFiles(resourcePath, "*.txt");
var prng = RandomNumberGenerator.Create(); // choose file if no arg provided
if(file == null)
// choose a file and line file = files[RandomNumberGenerator.GetInt32(files.Length)];
var file = files[RandomNumberGenerator.GetInt32(files.Length)]; // read the file and choose a line
var lines = File.ReadAllLines(file); var lines = File.ReadAllLines(file);
var line = lines[RandomNumberGenerator.GetInt32(lines.Length)]; var line = lines[RandomNumberGenerator.GetInt32(lines.Length)];
prng.Dispose(); // process line breaks
// process escape codes
line = line.Replace("\\n", "\n"); line = line.Replace("\\n", "\n");
// write // write the fortune
Console.WriteLine(line); Console.WriteLine(line);
return 0; return 0;

29
src/Util.cs Normal file
View file

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.IO;
public static class Utilities {
public static void Merge(params string[] files) {
// hashset to prevent duplicates
var members = new HashSet<string>();
// iterate over all paths given
foreach(var file in files) {
// skip nonexistent files gracefully
if(!File.Exists(file))
continue;
// iterate over lines
var lines = File.ReadAllLines(file);
foreach(var line in lines) {
// prevent duplicates
if(members.Contains(line))
continue;
members.Add(line);
// emit to stdout
Console.WriteLine(line);
}
}
}
}