about summary refs log tree commit diff stats
path: root/082persist.cc
diff options
context:
space:
mode:
authorKartik K. Agaram <vc@akkartik.com>2015-07-18 13:48:49 -0700
committerKartik K. Agaram <vc@akkartik.com>2015-07-18 13:48:49 -0700
commit13ba3defe91b4de6ab3da7e937ee448c49909725 (patch)
tree91f72461441aee148ad08f1efa544f880e6c725e /082persist.cc
parent8d9edfd6223d0f374404067eadc62171f915b76b (diff)
downloadmu-13ba3defe91b4de6ab3da7e937ee448c49909725.tar.gz
1814 - save code in editor
Very rudimentary ability to read/write from file+version control. No
control over name.

Recipes now saved. But what to do about sandboxes?
Diffstat (limited to '082persist.cc')
-rw-r--r--082persist.cc50
1 files changed, 50 insertions, 0 deletions
diff --git a/082persist.cc b/082persist.cc
new file mode 100644
index 00000000..3f9850fe
--- /dev/null
+++ b/082persist.cc
@@ -0,0 +1,50 @@
+//: Dead simple persistence.
+//:   'read' - reads string from a hardcoded file
+//:   'save' - writes string to a hardcoded file
+
+:(before "End Primitive Recipe Declarations")
+READ,
+:(before "End Primitive Recipe Numbers")
+Recipe_ordinal["read"] = READ;
+:(before "End Primitive Recipe Implementations")
+case READ: {
+  products.resize(1);
+  products.at(0).push_back(new_string(slurp("lesson/recipe.mu")));
+  break;
+}
+
+:(code)
+string slurp(const string& filename) {
+  ostringstream result;
+  ifstream fin(filename.c_str());
+  fin.peek();
+  if (!fin) return result.str();  // don't bother checking errno
+  const int N = 1024;
+  char buf[N];
+  while (!fin.eof()) {
+    bzero(buf, N);
+    fin.read(buf, N-1);  // leave at least one null
+    result << buf;
+  }
+  fin.close();
+  return result.str();
+}
+
+:(before "End Primitive Recipe Declarations")
+SAVE,
+:(before "End Primitive Recipe Numbers")
+Recipe_ordinal["save"] = SAVE;
+:(before "End Primitive Recipe Implementations")
+case SAVE: {
+  if (!scalar(ingredients.at(0)))
+    raise << "save: illegal operand " << current_instruction().ingredients.at(0).to_string() << '\n';
+  string contents = to_string(ingredients.at(0).at(0));
+  ofstream fout("lesson/recipe.mu");
+  fout << contents;
+  fout.close();
+  // bug in git: git diff -q messes up --exit-code
+  int status = system("cd lesson; git diff --exit-code >/dev/null || git commit -a -m . >/dev/null");
+  if (status != 0)
+    raise << "error in commit: contents " << contents << '\n';
+  break;
+}