Browse code

first public release

Olivier Lecointre authored on 22/09/2024 22:51:28
Showing 1 changed files
1 1
new file mode 100755
... ...
@@ -0,0 +1,566 @@
1
+/*
2
+ * valabuild.vala
3
+ * 
4
+ * Copyright 2018-2021 Olivier Lecointre <olivier[at]cadexis[dot]com>
5
+ * 
6
+ * This program is free software; you can redistribute it and/or modify
7
+ * it under the terms of the GNU General Public License as published by
8
+ * the Free Software Foundation; either version 3 of the License, or
9
+ * (at your option) any later version.
10
+ * 
11
+ * This program is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
+ * GNU General Public License for more details.
15
+ * 
16
+ * You should have received a copy of the GNU General Public License
17
+ * along with this program; if not see <http://www.gnu.org/licenses/>.
18
+ * 
19
+ */
20
+
21
+//Example of valac commands
22
+//valac --vapidir=../lib -X -I../lib -X -L../lib --pkg libgtkformhelper -X -lgtkformhelper -o valaman  valaman.vala
23
+//valac --vapidir=../lib -X -I../lib -X -L../lib --pkg libgtkformhelper -X -lgtkformhelper -o valaman  valaman.vala
24
+//valac --pkg gtk+-3.0 --pkg gmodule-2.0 --vapidir=../lib -X -I../lib -X -L../lib --pkg libgtkformhelper -X -lgtkformhelper -o valaman  valaman.vala testwin.vala --pkg libxml-2.0 --pkg libvala-0.26 --vapidir=/usr/local/share/vala-0.26/vapi
25
+//export LD_LIBRARY_PATH=/home/olivier/vdocs/Projects/vala/lib
26
+
27
+using Xml;
28
+using Xml.XPath;
29
+
30
+public class ValaBuild : GLib.Object
31
+{
32
+	public const string version = "0.1";
33
+	public const string copyright = "2018-2021 Cadexis Ltd";
34
+	
35
+	//Combines 2 parts of directories, if path 2 is not absolute
36
+	private string combine(string path1, string path2)
37
+	{
38
+		if (path2.index_of (Path.DIR_SEPARATOR_S)==0)
39
+		{
40
+			return path2;
41
+		}
42
+		else
43
+		{
44
+			 return Path.build_filename(path1,path2);
45
+		}
46
+	}
47
+	
48
+	public void build(string path)
49
+	{
50
+		//string curDir = runCommand("pwd");
51
+		//string curDir = Environment.get_current_dir();
52
+		//logMsg("Current directory %s",curDir);
53
+		
54
+		var directory = File.new_for_path (path);
55
+		var enumerator = directory.enumerate_children (FileAttribute.STANDARD_NAME, 0);
56
+
57
+		logMsg("Project directory %s",directory.get_path());
58
+
59
+		List<FileInfo> vlpList = new List<FileInfo> ();
60
+
61
+        FileInfo file_info;
62
+        while ((file_info = enumerator.next_file ()) != null) 
63
+        {
64
+			//logMsg(file_info.get_file_type());
65
+			//TODO: files doesn't seem to register here. Not sure why
66
+			//if (file_info.get_file_type()==FileType.REGULAR)
67
+			{
68
+				string name = file_info.get_name();
69
+				if (name!=null && name.length>4)
70
+				{
71
+					if (name.substring(-4,4)==".vlp")
72
+					{
73
+                        vlpList.append(file_info);
74
+					}
75
+				}
76
+				
77
+			}
78
+        }
79
+        
80
+        if (vlpList.length ()>0)
81
+        {
82
+            vlpList.foreach ((entry) => {
83
+                
84
+                string vlpPath = combine(directory.get_path(),entry.get_name());
85
+                string? targetGlib = null;
86
+                string? projectName = null;
87
+                string? projectType  = null;
88
+                string? outputdirectory = null;
89
+                string? buildscript = null;
90
+                string? startupscript = null;
91
+                logMsg("Found vlp file %s, processing it.",vlpPath);
92
+                GLib.HashTable<string, string?> project = getAttributes(vlpPath,"/project/name","type");
93
+                project.foreach ((key, val) =>
94
+                {
95
+                    projectName = key;
96
+                    projectType = val;
97
+                   
98
+                });
99
+                if (projectName==null)
100
+                {
101
+                    logMsg ("No project name defined");
102
+                    return;
103
+                }
104
+                if (projectType==null)
105
+                {
106
+                    logMsg ("No project type defined");
107
+                    return;
108
+                }
109
+                GLib.HashTable<string, string?> targets = getAttributes(vlpPath,"/project/targetglib",null);
110
+                targets.foreach ((key, val) =>
111
+                {
112
+                    targetGlib = key;
113
+                });
114
+                
115
+                GLib.HashTable<string, string?> buildscriptVal = getAttributes(vlpPath,"/project/buildscript",null);
116
+                buildscriptVal.foreach ((key, val) =>
117
+                {
118
+                    buildscript = key;
119
+                });
120
+                
121
+                GLib.HashTable<string, string?> startupscriptVal = getAttributes(vlpPath,"/project/startupscript",null);
122
+                startupscriptVal.foreach ((key, val) =>
123
+                {
124
+                    startupscript = key;
125
+                });
126
+                
127
+                GLib.HashTable<string, string?> outputdirectoryVal = getAttributes(vlpPath,"/project/copyoutput",null);
128
+                outputdirectoryVal.foreach ((key, val) =>
129
+                {
130
+                    outputdirectory = key;
131
+                });
132
+                
133
+                if (outputdirectory==null)
134
+                {
135
+                    outputdirectory = directory.get_path();
136
+                }
137
+                else
138
+                {
139
+                    outputdirectory = File.new_for_path (combine(directory.get_path(),outputdirectory)).get_path();
140
+                }
141
+                
142
+                logMsg ("Project Name: %s",projectName);
143
+                logMsg ("Project Type: %s",projectType);
144
+                
145
+                logMsg("-Package Dependencies");
146
+                GLib.HashTable<string, string?> dependencies = getAttributes(vlpPath,"/project/dependencies/dependency","installed");
147
+                dependencies.foreach ((key, val) =>
148
+                {
149
+                   logMsg ("%s => %s", key, val);
150
+                });
151
+                logMsg("-VAPI libraries");
152
+                GLib.HashTable<string, string?> vapi = getAttributes(vlpPath,"/project/dependencies/vapiroot","installed");
153
+                vapi.foreach ((key, val) =>
154
+                {
155
+                   logMsg ("%s => %s", key, val);
156
+                });
157
+                logMsg("-Source files");
158
+                GLib.HashTable<string, string?> sources = new GLib.HashTable<string, string?> (str_hash, str_equal);
159
+                GLib.HashTable<string, string?> sourceFiles = getAttributes(vlpPath,"/project/sources/file",null);
160
+                
161
+                sourceFiles.foreach ((key, val) =>
162
+                {
163
+                    if (key.contains("*"))
164
+                    {
165
+                        //set a file to understand the location of the pattern to check against
166
+                        File file = File.new_for_path (combine(directory.get_path(),key.replace("*","a")));
167
+                        File? dir = file.get_parent();
168
+                        if (dir!=null)
169
+                        {
170
+                            //List the files and check for the pattern
171
+                            FileEnumerator fileEnumerator = dir.enumerate_children (
172
+                                "standard::*",
173
+                                FileQueryInfoFlags.NOFOLLOW_SYMLINKS, 
174
+                                null);
175
+                            
176
+                            string matchKey = key.replace(".","""\.""").replace("*",""".+""");
177
+                            
178
+                            Regex wordRegex = new Regex (matchKey, RegexCompileFlags.CASELESS, RegexMatchFlags.NOTEMPTY);
179
+
180
+                            FileInfo info = null;
181
+                            MatchInfo matchInfo;
182
+                            while ((info = fileEnumerator.next_file (null)) != null) {
183
+                                
184
+                                wordRegex.match (info.get_name(), RegexMatchFlags.NOTEMPTY, out matchInfo);
185
+                                if (matchInfo.get_match_count ()>0)
186
+                                {
187
+                                    logMsg ("%s => %s", info.get_name(), val);
188
+                                    sources.set(info.get_name(),val);
189
+                                }
190
+                            }
191
+                        }
192
+                    }
193
+                    else
194
+                    {
195
+                        sources.set(key,val);
196
+                        logMsg ("%s => %s", key, val);
197
+                        
198
+                    }
199
+                });
200
+                string command = buildCommand(directory.get_path(),outputdirectory,projectName,projectType=="library",targetGlib,dependencies,vapi,sources);
201
+                logMsg("Command: %s",command);
202
+                
203
+                if (buildscript!=null)
204
+                {
205
+                    string buildscriptpath = combine(directory.get_path(),buildscript);
206
+                    saveBuildFile(buildscriptpath,command);
207
+                }
208
+                
209
+                if (startupscript!=null && projectType=="application")
210
+                {
211
+                    string startupscriptpath = combine(directory.get_path(),startupscript);
212
+                    saveStartupScript(startupscriptpath,directory.get_path(),projectName,vapi);
213
+                }
214
+                else if (startupscript!=null && projectType=="test")
215
+                {
216
+                    string startupscriptpath = combine(directory.get_path(),startupscript);
217
+                    saveTestScript(startupscriptpath,directory.get_path(),projectName,vapi);
218
+                }
219
+                
220
+                logMsg("Building");
221
+                runCommand(command);
222
+            });
223
+		}
224
+		else
225
+		{
226
+			logMsg("Cannot find any vlp file under %s",path);
227
+		}
228
+	}
229
+	
230
+	private void saveTestScript(string path,string rootPath, string projectName, GLib.HashTable<string, string?> vapi)
231
+	{
232
+		logMsg("Saving test script to %s",path);
233
+		try 
234
+		{
235
+			var file = File.new_for_path (path);
236
+			
237
+			if (file.query_exists ()) 
238
+			{
239
+				file.delete ();
240
+			}
241
+			
242
+			var dos = new DataOutputStream (file.create (FileCreateFlags.REPLACE_DESTINATION));
243
+			
244
+			dos.put_string ("#!/bin/sh\n");
245
+            dos.put_string ("export LAUNCHDIR=$PWD\n"); 
246
+            dos.put_string ("scriptdir=$(dirname ${0})\n");
247
+            dos.put_string ("canondir=$(readlink -f $scriptdir)\n");
248
+            dos.put_string ("cd $canondir\n");
249
+           
250
+			//dos.put_string ("cd  ");
251
+			//dos.put_string (rootPath);
252
+			//dos.put_string ("\n");
253
+			
254
+			vapi.foreach ((key, val) =>
255
+			{
256
+			   if (val!=null && val!="1")
257
+			   {
258
+				   dos.put_string ("export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:");
259
+				   dos.put_string (combine("$canondir",key));
260
+				   dos.put_string ("\n");
261
+			   }
262
+			});
263
+                        var valacDirectory = File.new_for_path(combine(GLib.Environment.get_home_dir(),"cadexis/vala"));
264
+			dos.put_string(combine(valacDirectory.get_path(),"gtester/gtester --verbose $@ "));	
265
+            		dos.put_string (combine("$canondir",projectName));
266
+			//dos.put_string (combine(rootPath,projectName));
267
+            FileUtils.chmod(path,0555);
268
+		} 
269
+		catch (GLib.Error e) 
270
+		{
271
+			logMsg("Error: %s", e.message);
272
+		}
273
+	}
274
+	
275
+	private void saveStartupScript(string path,string rootPath, string projectName, GLib.HashTable<string, string?> vapi)
276
+	{
277
+		logMsg("Saving startup script to %s",path);
278
+		try 
279
+		{
280
+			var file = File.new_for_path (path);
281
+			
282
+			if (file.query_exists ()) 
283
+			{
284
+				file.delete ();
285
+			}
286
+			
287
+			var dos = new DataOutputStream (file.create (FileCreateFlags.REPLACE_DESTINATION));
288
+			
289
+			dos.put_string ("#!/bin/sh\n");
290
+            dos.put_string ("export LAUNCHDIR=$PWD\n");
291
+            dos.put_string ("scriptdir=$(dirname ${0})\n");
292
+            dos.put_string ("canondir=$(readlink -f $scriptdir)\n");
293
+            dos.put_string ("cd $canondir\n");
294
+            var valacDirectory = File.new_for_path(combine(GLib.Environment.get_home_dir(),"cadexis/vala"));
295
+	    dos.put_string("export GIO_MODULE_DIR="+combine(valacDirectory.get_path(),"valac/giomodules\n")); 
296
+	    dos.put_string("export GSETTINGS_SCHEMA_DIR="+combine(valacDirectory.get_path(),"valac/gschemas\n"));
297
+            			
298
+			//dos.put_string ("cd  ");
299
+			//dos.put_string (rootPath);
300
+			//dos.put_string ("\n");
301
+			
302
+			vapi.foreach ((key, val) =>
303
+			{
304
+			   if (val!=null && val!="1")
305
+			   {
306
+				   dos.put_string ("export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:");
307
+				   dos.put_string (combine("$canondir",key));
308
+				   dos.put_string ("\n");
309
+			   }
310
+			});
311
+            dos.put_string (combine("$canondir",projectName));
312
+			//dos.put_string (combine(rootPath,projectName));
313
+			dos.put_string (" $@");
314
+            FileUtils.chmod(path,0555);
315
+		} 
316
+		catch (GLib.Error e) 
317
+		{
318
+			logMsg("Error: %s", e.message);
319
+		}
320
+	}
321
+	
322
+	private void saveBuildFile(string path, string command)
323
+	{
324
+		logMsg("Saving build command to %s",path);
325
+		try 
326
+		{
327
+			var file = File.new_for_path (path);
328
+			
329
+			if (file.query_exists ()) 
330
+			{
331
+				file.delete ();
332
+			}
333
+
334
+			var dos = new DataOutputStream (file.create (FileCreateFlags.REPLACE_DESTINATION));
335
+			dos.put_string (command);
336
+            FileUtils.chmod(path,0555);
337
+		} 
338
+		catch (GLib.Error e) 
339
+		{
340
+			logMsg("Error: %s", e.message);
341
+		}
342
+	}
343
+    
344
+    private string getLibName(string name)
345
+    {
346
+        if (name.length>3)
347
+        {
348
+            if (name.index_of("lib")==0)
349
+            {
350
+                return name.substring(3);
351
+            }
352
+        }
353
+        return name;
354
+    }
355
+    
356
+	
357
+	private string buildCommand(string srcRoot,string outputpath,string projectName, bool isLibrary, 
358
+		string? targetGlib,
359
+		GLib.HashTable<string, string?> dependency, 
360
+		GLib.HashTable<string, string?> vapi,
361
+		GLib.HashTable<string, string?> source)
362
+	{
363
+		StringBuilder builder = new StringBuilder ();
364
+		var valacDirectory = File.new_for_path(combine(GLib.Environment.get_home_dir(),"cadexis/vala")); 
365
+		builder.append(combine(valacDirectory.get_path(),"valac/valac"));
366
+		builder.append(" -X -lm");
367
+		
368
+		if (targetGlib!=null)
369
+		{
370
+			builder.append(" --target-glib ");
371
+			builder.append(targetGlib);
372
+		}
373
+		
374
+		dependency.foreach ((key, val) =>
375
+		{
376
+		   if (val==null || val!="2")
377
+		   {
378
+			   builder.append(" --pkg=");
379
+			   builder.append(key);
380
+		   }
381
+		   if (val!=null && val!="1")
382
+		   {
383
+			   builder.append(" -X -l");
384
+			   builder.append(getLibName(key));
385
+		   }
386
+		});
387
+		
388
+	 	builder.append(" -X -l");
389
+		builder.append("gio-2.0");
390
+		//builder.append(" -X -lposix"); 
391
+	
392
+		//This part is to integrate environment where vala is not installed using apt	
393
+		builder.append(" --vapidir=");
394
+		builder.append(combine(valacDirectory.get_path(),"valac/vapi"));
395
+		builder.append(" -X -I");
396
+		builder.append(combine(valacDirectory.get_path(),"valac/include/glib-2.0"));
397
+		builder.append(" -X -I");
398
+		builder.append(combine(valacDirectory.get_path(),"valac/include/gee-0.8"));
399
+		builder.append(" -X -I");
400
+		builder.append(combine(valacDirectory.get_path(),"valac/include/libxml2"));
401
+		builder.append(" -X -I");
402
+		builder.append(combine(valacDirectory.get_path(),"valac/include/json-glib-1.0"));
403
+		builder.append(" -X -I");
404
+		builder.append(combine(valacDirectory.get_path(),"valac/include/libsoup-2.4"));
405
+		builder.append(" -X -I");
406
+		builder.append(combine(valacDirectory.get_path(),"valac/include"));
407
+		builder.append(" -X -L");
408
+		builder.append(combine(valacDirectory.get_path(),"lib"));
409
+
410
+		GLib.Environment.set_variable("PKG_CONFIG_PATH",combine(valacDirectory.get_path(),"valac/pkgconfig"),true);
411
+		GLib.Environment.set_variable("LD_LIBRARY_PATH",combine(valacDirectory.get_path(),"valac")+":"+combine(valacDirectory.get_path(),"lib"),true);
412
+	
413
+		vapi.foreach ((key, val) =>
414
+		{
415
+		   string path = combine(srcRoot,key);
416
+		   builder.append(" --vapidir=");
417
+		   builder.append(path);
418
+		   if (val!=null && val!="1")
419
+		   {
420
+			   builder.append(" -X -I");
421
+			   builder.append(path);
422
+			   builder.append(" -X -L");
423
+			   builder.append(path);
424
+		   }
425
+		});
426
+		
427
+		if (isLibrary)
428
+		{
429
+			builder.append(" --library=");
430
+			builder.append(projectName);
431
+			builder.append(" --vapi=");
432
+			builder.append(combine(outputpath,projectName));
433
+			builder.append(".vapi -H ");
434
+			builder.append(combine(outputpath,projectName));
435
+			builder.append(".h -X -fPIC -X -shared -o ");
436
+			builder.append(combine(outputpath,projectName));
437
+			builder.append(".so ");
438
+		}
439
+		else
440
+		{
441
+			builder.append(" -o ");
442
+			builder.append(combine(outputpath,projectName));
443
+		}
444
+		
445
+		source.foreach ((key, val) =>
446
+		{
447
+		    builder.append(" ");
448
+		    builder.append(combine(srcRoot,key));
449
+		});
450
+		
451
+		return (owned) builder.str;
452
+	}
453
+	
454
+	private string runCommand(string cmd)
455
+	{
456
+		string execute = cmd;
457
+		string output = "";
458
+		string err = "";
459
+		int exitcode = -1;
460
+		bool result= false;
461
+
462
+		try 
463
+		{
464
+			result= GLib.Process.spawn_command_line_sync(execute, out output, out err, out exitcode);
465
+		} 
466
+		catch (SpawnError e) 
467
+		{
468
+			logMsg("spawn error!\n"+e.message);
469
+		}
470
+
471
+		logMsg("Output: %s\nError: %s\nExitcode: %s\nResult: %s\n", output,err,exitcode.to_string(), result.to_string());
472
+		
473
+		return output;
474
+	}
475
+}
476
+
477
+public static GLib.HashTable<string, string?> getAttributes(string filePath, string xpath, string? attrName)
478
+{
479
+	GLib.HashTable<string, string?> retHashtable = new GLib.HashTable<string, string?> (str_hash, str_equal);
480
+	
481
+	//https://wiki.gnome.org/Projects/Vala/XmlSample
482
+	
483
+	Xml.Doc* doc = Parser.parse_file (filePath);
484
+	if(doc==null) logMsg("failed to read the .xml file");
485
+
486
+	Context ctx = new Context(doc);
487
+	if(ctx==null) logMsg("failed to create the xpath context");
488
+
489
+	Xml.XPath.Object* obj = ctx.eval_expression(xpath);
490
+	if(obj==null)
491
+	{
492
+		logMsg("failed to evaluate xpath");
493
+	}
494
+
495
+	Xml.Node* node = null;
496
+	
497
+	if ( obj->nodesetval != null)
498
+	{
499
+		int numControls = obj->nodesetval->length();
500
+		for (int i=0;i<numControls;i++)
501
+		{	
502
+			node = obj->nodesetval->item(i);
503
+			string nodeVal = node->get_content();
504
+			string attrVal = null;
505
+			if (attrName!=null)
506
+			{			
507
+				Xml.Attr* attr = null;
508
+				attr = node->properties;
509
+				while ( attr != null )
510
+				{
511
+					if (attr->name == attrName)
512
+					{
513
+						attrVal = attr->children->content;
514
+					}
515
+					attr = attr->next;
516
+				}
517
+			}
518
+			retHashtable.insert (nodeVal, attrVal);
519
+		}
520
+	} 
521
+	else 
522
+	{
523
+			logMsg("failed to find the expected node");
524
+	}
525
+	
526
+	
527
+	delete obj;
528
+	delete doc;
529
+	
530
+	return retHashtable;
531
+}
532
+
533
+public static void logMsg(string msg,...)
534
+{
535
+	var va_list = va_list ();
536
+	StringBuilder builder = new StringBuilder ();
537
+	builder.append_vprintf (msg+"\n", va_list);
538
+	stderr.printf((owned) builder.str);
539
+}
540
+
541
+ValaBuild man = null;
542
+
543
+int main (string[] args) 
544
+{    
545
+	if (args==null || args.length<2)
546
+	{
547
+		logMsg("valabuild - version %s".printf(ValaBuild.version));
548
+		logMsg("Copyright (C) %s".printf(ValaBuild.copyright));
549
+		logMsg("Tool to facilitate vala building.");
550
+		logMsg("\nusage: valabuild directory_path");
551
+		return 1;
552
+	}
553
+	try 
554
+	{
555
+        string path = args[1];
556
+		logMsg("Building %s",path);
557
+		man = new ValaBuild();
558
+		man.build(path);
559
+		return 0;
560
+    } 
561
+    catch (GLib.Error e) 
562
+    {
563
+        stderr.printf ("Error: %s\n", e.message);
564
+        return 1;
565
+    }
566
+}