httpcompiler.pp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. unit httpcompiler;
  2. {$mode objfpc}
  3. {$H+}
  4. interface
  5. uses
  6. sysutils, classes, fpjson, contnrs, syncobjs, custhttpapp, fpwebfile, httproute,
  7. pas2jscompiler, httpdefs, dirwatch;
  8. Const
  9. nErrTooManyThreads = -1;
  10. Type
  11. TDirWatcher = Class;
  12. THTTPCompilerApplication = Class;
  13. { TCompileItem }
  14. TCompileItem = Class(TCollectionItem)
  15. private
  16. FBaseDir: string;
  17. FConfigFile: String;
  18. FFileName: string;
  19. FOutput : TStrings;
  20. FOptions : TStrings;
  21. FSuccess: Boolean;
  22. FThread: TThread;
  23. function GetOptions: TStrings;
  24. function GetOutput: TStrings;
  25. Public
  26. Destructor Destroy; override;
  27. Property BaseDir : string Read FBaseDir Write FBaseDir;
  28. Property FileName : string Read FFileName Write FFileName;
  29. Property ConfigFile: String Read FConfigFile Write FConfigFile;
  30. Property Options : TStrings Read GetOptions;
  31. Property Output : TStrings Read GetOutput;
  32. Property Thread : TThread Read FThread;
  33. Property Success : Boolean Read FSuccess;
  34. end;
  35. { TCompiles }
  36. TCompiles = Class(TCollection)
  37. private
  38. function GetC(AIndex : Integer): TCompileItem;
  39. Public
  40. Property Compiles[AIndex : Integer] : TCompileItem Read GetC; default;
  41. end;
  42. { TCompileThread }
  43. TCompileThread = class(TThread)
  44. private
  45. FApp : THTTPCompilerApplication;
  46. FItem: TCompileItem;
  47. procedure DoCompilerLog(Sender: TObject; const Msg: String);
  48. procedure SetItem(AValue: TCompileItem);
  49. Public
  50. Constructor create(App : THTTPCompilerApplication; aItem : TCompileItem);
  51. Procedure Execute; override;
  52. Property Item : TCompileItem read FItem write SetItem;
  53. end;
  54. { TDirWatcher }
  55. TDirWatcher = Class(TComponent)
  56. Private
  57. FApp : THTTPCompilerApplication;
  58. FDW : TDirWatch;
  59. procedure DoChange(Sender: TObject; aEntry: TDirectoryEntry; AEvents: TFileEvents);
  60. Public
  61. Constructor Create(App : THTTPCompilerApplication; ADir : String);overload;
  62. Destructor Destroy; override;
  63. end;
  64. { THTTPCompilerApplication }
  65. THTTPCompilerApplication = Class(TCustomHTTPApplication)
  66. private
  67. FBaseDir: String;
  68. FConfigFile: String;
  69. FProjectFile: String;
  70. FStatusLock : TCriticalSection;
  71. FQuiet: Boolean;
  72. FWatch: Boolean;
  73. FDW : TDirWatcher;
  74. FStatusList : TFPObjectList;
  75. FCompiles : TCompiles;
  76. procedure AddToStatus(O: TJSONObject);
  77. Procedure ReportBuilding(AItem : TCompileItem);
  78. Procedure ReportBuilt(AItem : TCompileItem);
  79. Procedure AddToStatus(AEntry : TDirectoryEntry; AEvents : TFileEvents);
  80. procedure DoStatusRequest(ARequest: TRequest; AResponse: TResponse);
  81. procedure DoRecompile(ARequest: TRequest; AResponse: TResponse);
  82. function ScheduleCompile(const aProjectFile: String; Options : TStrings = Nil): Integer;
  83. procedure StartWatch(ADir: String);
  84. procedure Usage(Msg: String);
  85. public
  86. Constructor Create(AOWner : TComponent); override;
  87. Destructor Destroy; override;
  88. procedure DoLog(EventType: TEventType; const Msg: String); override;
  89. Procedure DoRun; override;
  90. property Quiet : Boolean read FQuiet Write FQuiet;
  91. Property Watch : Boolean Read FWatch Write FWatch;
  92. Property ProjectFile : String Read FProjectFile Write FProjectFile;
  93. Property ConfigFile : String Read FConfigFile Write FConfigFile;
  94. Property BaseDir : String Read FBaseDir;
  95. end;
  96. Implementation
  97. { TCompileThread }
  98. procedure TCompileThread.SetItem(AValue: TCompileItem);
  99. begin
  100. if FItem=AValue then Exit;
  101. FItem:=AValue;
  102. end;
  103. procedure TCompileThread.DoCompilerLog(Sender: TObject; const Msg: String);
  104. begin
  105. If Assigned(Item) then
  106. Item.Output.Add(Msg);
  107. end;
  108. constructor TCompileThread.create(App: THTTPCompilerApplication; aItem: TCompileItem);
  109. begin
  110. FItem:=aItem;
  111. FApp:=App;
  112. FreeOnTerminate:=True;
  113. inherited create(False);
  114. end;
  115. procedure TCompileThread.Execute;
  116. Var
  117. C : TPas2jsCompiler;
  118. L : TStrings;
  119. begin
  120. L:=Nil;
  121. C:=TPas2jsCompiler.Create;
  122. Try
  123. FApp.ReportBuilding(Item);
  124. L:=TStringList.Create;
  125. L.Assign(Item.Options);
  126. if (Item.ConfigFile<>'') then
  127. L.Add('@'+Item.ConfigFile);
  128. L.Add(Item.FileName);
  129. C.Log.OnLog:=@DoCompilerLog;
  130. try
  131. C.Run(ParamStr(0),Item.BaseDir,L,True);
  132. Item.FSuccess:=True;
  133. except
  134. On E : Exception do
  135. Item.Output.Add(Format('Error %s compiling %s: %s',[E.ClassName,Item.FileName,E.Message]));
  136. end;
  137. FApp.ReportBuilt(Item);
  138. Finally
  139. C.Free;
  140. L.Free;
  141. end;
  142. Item.FThread:=Nil;
  143. end;
  144. { TCompiles }
  145. function TCompiles.GetC(AIndex : Integer): TCompileItem;
  146. begin
  147. Result:=Items[Aindex] as TCompileItem;
  148. end;
  149. { TCompileItem }
  150. function TCompileItem.GetOutput: TStrings;
  151. begin
  152. If (FOutput=Nil) then
  153. FOutput:=TStringList.Create;
  154. Result:=FOutput;
  155. end;
  156. function TCompileItem.GetOptions: TStrings;
  157. begin
  158. If (FOptions=Nil) then
  159. FOptions:=TStringList.Create;
  160. Result:=FOptions;
  161. end;
  162. destructor TCompileItem.Destroy;
  163. begin
  164. FreeAndNil(FOutput);
  165. FreeAndNil(FOptions);
  166. inherited Destroy;
  167. end;
  168. { TDirWatcher }
  169. procedure TDirWatcher.DoChange(Sender: TObject; aEntry: TDirectoryEntry; AEvents: TFileEvents);
  170. begin
  171. if Assigned(FApp) then
  172. FApp.AddToStatus(AEntry,AEvents);
  173. end;
  174. constructor TDirWatcher.Create(App: THTTPCompilerApplication; ADir: String);
  175. begin
  176. Inherited create(APP);
  177. FApp:=App;
  178. FDW:=TDirwatch.Create(Self);
  179. FDW.AddWatch(ADir,allEvents);
  180. FDW.OnChange:=@DoChange;
  181. TThread.ExecuteInThread(@FDW.StartWatch);
  182. end;
  183. destructor TDirWatcher.Destroy;
  184. begin
  185. FApp:=Nil;
  186. FDW.Terminate;
  187. FreeAndNil(FDW);
  188. inherited Destroy;
  189. end;
  190. { THTTPCompilerApplication }
  191. procedure THTTPCompilerApplication.DoLog(EventType: TEventType; const Msg: String);
  192. begin
  193. if Quiet then
  194. exit;
  195. if IsConsole then
  196. Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz',Now),' [',EventType,'] ',Msg)
  197. else
  198. inherited DoLog(EventType, Msg);
  199. end;
  200. procedure THTTPCompilerApplication.Usage(Msg : String);
  201. begin
  202. if (Msg<>'') then
  203. Writeln('Error: ',Msg);
  204. Writeln('Usage ',ExtractFileName(ParamStr(0)),' [options] ');
  205. Writeln('Where options is one or more of : ');
  206. Writeln('-d --directory=dir Base directory from which to serve files.');
  207. Writeln(' Default is current working directory: ',GetCurrentDir);
  208. Writeln('-h --help This help text');
  209. Writeln('-i --indexpage=name Directory index page to use (default: index.html)');
  210. Writeln('-n --noindexpage Do not allow index page.');
  211. Writeln('-p --port=NNNN TCP/IP port to listen on (default is 3000)');
  212. Writeln('-q --quiet Do not write diagnostic messages');
  213. Writeln('-w --watch Watch directory for changes');
  214. Writeln('-c --compile[=proj] Recompile project if pascal files change. Default project is app.lpr');
  215. Halt(Ord(Msg<>''));
  216. end;
  217. constructor THTTPCompilerApplication.Create(AOWner: TComponent);
  218. begin
  219. inherited Create(AOWner);
  220. FStatusLock:=TCriticalSection.Create;
  221. FStatusList:=TFPObjectList.Create(False);
  222. FCompiles:=TCompiles.Create(TCompileItem);
  223. end;
  224. destructor THTTPCompilerApplication.Destroy;
  225. begin
  226. FStatusLock.Enter;
  227. try
  228. FreeAndNil(FCompiles);
  229. FreeAndNil(FStatusList);
  230. finally
  231. FStatusLock.Leave;
  232. end;
  233. FreeAndNil(FStatusLock);
  234. inherited Destroy;
  235. end;
  236. procedure THTTPCompilerApplication.StartWatch(ADir : String);
  237. begin
  238. FDW:=TDirWatcher.Create(Self,ADir);
  239. end;
  240. procedure THTTPCompilerApplication.ReportBuilding(AItem: TCompileItem);
  241. Var
  242. O : TJSONObject;
  243. begin
  244. O:=TJSONObject.Create(['action','building','compileID',AItem.ID,'project',AItem.FileName,'config',AItem.ConfigFile]);
  245. AddToStatus(O);
  246. end;
  247. procedure THTTPCompilerApplication.ReportBuilt(AItem: TCompileItem);
  248. Var
  249. O : TJSONObject;
  250. A : TJSONArray;
  251. I : Integer;
  252. begin
  253. A:=TJSONArray.Create;
  254. For I:=0 to AItem.Output.Count-1 do
  255. A.Add(AItem.Output[i]);
  256. O:=TJSONObject.Create(['action','built','compileID',AItem.ID,'project',AItem.FileName,'config',AItem.ConfigFile,'output',A,'success',AItem.Success]);
  257. AddToStatus(O);
  258. end;
  259. procedure THTTPCompilerApplication.AddToStatus(O : TJSONObject);
  260. begin
  261. FStatusLock.Enter;
  262. try
  263. Writeln('Adding to status ',Assigned(O),' : ',O.ClassName);
  264. FStatusList.Add(O);
  265. finally
  266. FStatusLock.Leave;
  267. end;
  268. end;
  269. procedure THTTPCompilerApplication.AddToStatus(AEntry: TDirectoryEntry; AEvents: TFileEvents);
  270. Var
  271. O : TJSONObject;
  272. FN : String;
  273. begin
  274. Log(etDebug,'File change detected: %s (%s)',[AEntry.name,FileEventsToStr(AEvents)]);
  275. O:=TJSONObject.Create(['action','file','name',AEntry.name,'events',FileEventsToStr(AEvents)]);
  276. if Pos(ExtractFileExt(AEntry.Name),'.lpr.pas.pp.inc.dpr')>0 then
  277. FN:=AEntry.Name;
  278. if (FN<>'') then
  279. O.Add('recompile',true);
  280. AddToStatus(O);
  281. if (FN<>'') then
  282. begin
  283. Log(etDebug,'File change forces recompile: %s',[AEntry.name]);
  284. ScheduleCompile('',Nil);
  285. end;
  286. end;
  287. procedure THTTPCompilerApplication.DoStatusRequest(ARequest : TRequest; AResponse : TResponse);
  288. Var
  289. R,O : TJSONObject;
  290. A : TJSONArray;
  291. I : integer;
  292. begin
  293. Log(etDebug,'Status request from: %s',[ARequest.RemoteAddress]);
  294. R:=Nil;
  295. try
  296. FStatusLock.Enter;
  297. try
  298. if (FStatusList.Count=0) then
  299. R:=TJSONObject.Create(['ping',True])
  300. else
  301. begin
  302. Writeln(FStatusList[0].ClassName);
  303. O:=FStatusList[0] as TJSONObject;
  304. FStatusList.Delete(0);
  305. if O.Get('action','')<>'file' then
  306. R:=O
  307. else
  308. begin
  309. // If first event is file event, then add and delete all file events in list.
  310. A:=TJSONArray.Create([O]);
  311. O.Delete('action');
  312. R:=TJSONObject.Create(['action','sync','files',A]);
  313. For I:=FStatusList.Count-1 downto 0 do
  314. begin
  315. O:=FStatusList[I] as TJSONObject;
  316. if (O.Get('action','')='file') then
  317. begin
  318. A.Add(O);
  319. O.Delete('action');
  320. FStatusList.Delete(I);
  321. end;
  322. end;
  323. end
  324. end;
  325. finally
  326. FStatusLock.Leave;
  327. end;
  328. AResponse.ContentType:='application/json';
  329. AResponse.Content:=R.AsJSON;
  330. AResponse.SendResponse;
  331. finally
  332. R.Free;
  333. end;
  334. end;
  335. Function THTTPCompilerApplication.ScheduleCompile(const aProjectFile : String; Options : TStrings = Nil) : Integer;
  336. Var
  337. CI : TCompileItem;
  338. I,TC : Integer;
  339. begin
  340. TC:=0;
  341. For I:=0 to FCompiles.Count-1 do
  342. if Assigned(FCompiles[I].THread) then
  343. Inc(TC);
  344. if TC>10 then
  345. begin
  346. Log(etError,'Refusing compile of file "%s" using config file "%s"',[AProjectFile, ConfigFile]);
  347. Exit(nErrTooManyThreads);
  348. end;
  349. CI:=FCompiles.Add as TCompileItem;
  350. Log(etInfo,'Scheduling compile ID %d of file "%s" using config file "%s"',[CI.ID,AProjectFile, ConfigFile]);
  351. CI.BaseDir:=BaseDir;
  352. CI.FileName:=AProjectFile;
  353. CI.ConfigFile:=ConfigFile;
  354. if Assigned(Options) then
  355. CI.Options.Assign(Options);
  356. TCompileThread.Create(Self,CI);
  357. Result:=CI.ID;
  358. end;
  359. procedure THTTPCompilerApplication.DoRecompile(ARequest: TRequest; AResponse: TResponse);
  360. Var
  361. ID : Integer;
  362. PF,CL : String;
  363. Options: TStrings;
  364. begin
  365. PF:=ARequest.ContentFields.Values['ProjectFile'];
  366. CL:=ARequest.ContentFields.Values['CompileOptions'];
  367. if PF='' then
  368. PF:=ProjectFile;
  369. If (PF='') then
  370. begin
  371. AResponse.Code:=404;
  372. AResponse.CodeText:='No project file';
  373. AResponse.ContentType:='application/json';
  374. AResponse.Content:='{ "success" : false, "message": "no project file set or provided" }';
  375. end
  376. else
  377. begin
  378. Options:=Nil;
  379. try
  380. if CL<>'' then
  381. begin
  382. Options:=TStringList.Create;
  383. Options.Text:=Cl;
  384. end;
  385. ID:=ScheduleCompile(PF,Options);
  386. finally
  387. FreeAndNil(Options);
  388. end;
  389. if ID=nErrTooManyThreads then
  390. begin
  391. AResponse.Code:=403;
  392. AResponse.CodeText:='Too many compiles';
  393. AResponse.ContentType:='application/json';
  394. AResponse.Content:='{ "success" : false, "message": "Too many compiles running" }';
  395. end
  396. else
  397. begin
  398. AResponse.Code:=200;
  399. AResponse.ContentType:='application/json';
  400. AResponse.Content:=Format('{ "success" : true, "file": "%s", "commandLine" : "%s", "compileID": %d }',[StringToJSONString(PF),StringToJSONString(CL),ID]);
  401. end
  402. end;
  403. AResponse.SendResponse;
  404. end;
  405. procedure THTTPCompilerApplication.DoRun;
  406. Var
  407. S,IndexPage,D : String;
  408. begin
  409. S:=Checkoptions('hqd:ni:p:wP::c',['help','quiet','noindexpage','directory:','port:','indexpage:','watch','project::','config:']);
  410. if (S<>'') or HasOption('h','help') then
  411. usage(S);
  412. Quiet:=HasOption('q','quiet');
  413. Watch:=HasOption('w','watch');
  414. Port:=StrToIntDef(GetOptionValue('p','port'),3000);
  415. D:=GetOptionValue('d','directory');
  416. if D='' then
  417. D:=GetCurrentDir;
  418. Log(etInfo,'Listening on port %d, serving files from directory: %s',[Port,D]);
  419. {$ifdef unix}
  420. MimeTypesFile:='/etc/mime.types';
  421. {$endif}
  422. if Hasoption('P','project') then
  423. begin
  424. ProjectFile:=GetOptionValue('P','project');
  425. if ProjectFile='' then
  426. ProjectFile:=IncludeTrailingPathDelimiter(D)+'app.lpr';
  427. If Not FileExists(ProjectFile) then
  428. begin
  429. Terminate;
  430. Log(etError,'Project file "%s" does not exist, aborting.',[ProjectFile]);
  431. Exit;
  432. end;
  433. ConfigFile:=GetOptionValue('c','config');
  434. if (ConfigFile='') then
  435. ConfigFile:=ChangeFileExt(Projectfile,'.cfg');
  436. if not FileExists(ConfigFile) then
  437. ConfigFile:='';
  438. end;
  439. if Watch then
  440. begin
  441. if (ProjectFile='') then
  442. Log(etWarning,'No project file specified, disabling watch.') ;
  443. StartWatch(D);
  444. end;
  445. FBaseDir:=D;
  446. TSimpleFileModule.BaseDir:=IncludeTrailingPathDelimiter(D);
  447. TSimpleFileModule.OnLog:=@Log;
  448. If not HasOption('n','noindexpage') then
  449. begin
  450. IndexPage:=GetOptionValue('i','indexpage');
  451. if (IndexPage='') then
  452. IndexPage:='index.html';
  453. Log(etInfo,'Using index page %s',[IndexPage]);
  454. TSimpleFileModule.IndexPageName:=IndexPage;
  455. end;
  456. httprouter.RegisterRoute('$sys/compile',rmPost,@DoRecompile);
  457. httprouter.RegisterRoute('$sys/status',rmGet,@DoStatusRequest);
  458. TSimpleFileModule.RegisterDefaultRoute;
  459. inherited;
  460. end;
  461. end.