shithub: spread

Download patch

ref: 39a4f1b284bab0a4587a845c53cdb53bcae625c8
parent: b16375893ad58a69c9797fb76c97631de0513eb0
author: sirjofri <[email protected]>
date: Thu Jul 4 06:39:50 EDT 2024

adds writefile support

--- a/cells.c
+++ b/cells.c
@@ -90,7 +90,7 @@
 }
 
 void
-foreachcell(void (*f)(Cell*))
+foreachcell(void (*f)(Cell*,void*), void *aux)
 {
 	int i;
 	Cell *c;
@@ -99,7 +99,7 @@
 		c = &block.cells[i];
 		if (c->type != FUNCTION && c->type != STRING)
 			continue;
-		f(c);
+		f(c, aux);
 	}
 }
 
@@ -152,7 +152,7 @@
 }
 
 static void
-celldeps(Cell* c)
+celldeps(Cell* c, void*)
 {
 	Cell *d;
 	char *s;
@@ -208,7 +208,7 @@
 	
 	// build DAG information
 	funcregexp = regcomp("[A-Z]+[0-9]+[(]+[)]+");
-	foreachcell(celldeps);
+	foreachcell(celldeps, nil);
 	free(funcregexp);
 	funcregexp = nil;
 	
--- a/engine.c
+++ b/engine.c
@@ -6,6 +6,7 @@
 char Einitengine[] = "initengine: %r";
 
 int p[3];
+char *preamble;
 
 typedef struct Strchan Strchan;
 struct Strchan {
@@ -263,7 +264,7 @@
 char Hstring[] = "func %s() { print \"%s\" }\n";
 
 static void
-sendctohoc(Cell *c)
+sendctohoc(Cell *c, void*)
 {
 	char *h;
 	char *buf;
@@ -308,6 +309,19 @@
 	addcell(p, a, type);
 }
 
+static void
+appendpreamble(char *s)
+{
+	char *t;
+	if (!preamble) {
+		preamble = strdup(s);
+		return;
+	}
+	t = preamble;
+	preamble = smprint("%s%s", preamble, s);
+	free(t);
+}
+
 int
 loadfile(char *file)
 {
@@ -327,6 +341,7 @@
 			break;
 		}
 		
+		appendpreamble(s);
 		hocwrite(s, nil);
 		free(s);
 	}
@@ -351,8 +366,53 @@
 	
 	sortcells();
 	
-	foreachcell(sendctohoc);
+	foreachcell(sendctohoc, nil);
 	
+	return 1;
+}
+
+static void
+writecell(Cell *c, void *aux)
+{
+	Biobuf *b = (Biobuf*)aux;
+	
+	switch (c->type) {
+	case FUNCTION:
+		Bprint(b, "%s=%s\n", ptoa(c->p), c->value);
+		break;
+	case STRING:
+		Bprint(b, "%s;%s\n", ptoa(c->p), c->value);
+		break;
+	}
+}
+
+int
+writefile(char *file)
+{
+	Biobuf *bout;
+	int fd;
+	
+	bout = Bopen(file, OWRITE);
+	
+	if (!bout) {
+		fd = create(file, OWRITE, 0666);
+		if (fd < 0) {
+			werrstr("unable to create file: %r");
+			return 0;
+		}
+		bout = Bfdopen(fd, OWRITE);
+		if (!bout) {
+			werrstr("error: %r");
+			return 0;
+		}
+	}
+	
+	Bprint(bout, "%s", preamble);
+	Bprint(bout, "%%%%%%\n");
+	
+	foreachcell(writecell, bout);
+	
+	Bterm(bout);
 	return 1;
 }
 
--- a/spread.c
+++ b/spread.c
@@ -42,8 +42,6 @@
 	if (!loadfile(file))
 		sysfatal("%r");
 	
-//	dumpcells();
-	
 	if (interactive) {
 		interactivehoc();
 		exits(nil);
@@ -52,4 +50,6 @@
 	Response r = getvalue("a4");
 	
 	fprint(2, "value: A4='%s' (error=%d)\n", r.msg, r.error);
+	
+	writefile("/tmp/testout");
 }
--- a/spread.h
+++ b/spread.h
@@ -19,7 +19,7 @@
 Cell* getcell(P cell);
 void gccells(void);
 void dumpcells(void);
-void foreachcell(void (*f)(Cell*));
+void foreachcell(void (*f)(Cell*,void*), void*);
 void sortcells(void);
 
 void toupperil(char*);