httpcompiler.pp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. FServeOnly : Boolean;
  77. procedure AddToStatus(O: TJSONObject);
  78. function HandleCompileOptions(aDir: String): Boolean;
  79. function ProcessOptions: Boolean;
  80. Procedure ReportBuilding(AItem : TCompileItem);
  81. Procedure ReportBuilt(AItem : TCompileItem);
  82. Procedure AddToStatus(AEntry : TDirectoryEntry; AEvents : TFileEvents);
  83. procedure DoStatusRequest(ARequest: TRequest; AResponse: TResponse);
  84. procedure DoRecompile(ARequest: TRequest; AResponse: TResponse);
  85. function ScheduleCompile(const aProjectFile: String; Options : TStrings = Nil): Integer;
  86. procedure StartWatch(ADir: String);
  87. procedure Usage(Msg: String);
  88. public
  89. Constructor Create(AOWner : TComponent); override;
  90. Destructor Destroy; override;
  91. procedure DoLog(EventType: TEventType; const Msg: String); override;
  92. Procedure DoRun; override;
  93. property Quiet : Boolean read FQuiet Write FQuiet;
  94. Property Watch : Boolean Read FWatch Write FWatch;
  95. Property ProjectFile : String Read FProjectFile Write FProjectFile;
  96. Property ConfigFile : String Read FConfigFile Write FConfigFile;
  97. Property BaseDir : String Read FBaseDir;
  98. Property ServeOnly : Boolean Read FServeOnly;
  99. end;
  100. Implementation
  101. { TCompileThread }
  102. procedure TCompileThread.SetItem(AValue: TCompileItem);
  103. begin
  104. if FItem=AValue then Exit;
  105. FItem:=AValue;
  106. end;
  107. procedure TCompileThread.DoCompilerLog(Sender: TObject; const Msg: String);
  108. begin
  109. If Assigned(Item) then
  110. Item.Output.Add(Msg);
  111. end;
  112. constructor TCompileThread.create(App: THTTPCompilerApplication; aItem: TCompileItem);
  113. begin
  114. FItem:=aItem;
  115. FApp:=App;
  116. FreeOnTerminate:=True;
  117. inherited create(False);
  118. end;
  119. procedure TCompileThread.Execute;
  120. Var
  121. C : TPas2jsCompiler;
  122. L : TStrings;
  123. begin
  124. L:=Nil;
  125. C:=TPas2jsCompiler.Create;
  126. Try
  127. FApp.ReportBuilding(Item);
  128. L:=TStringList.Create;
  129. L.Assign(Item.Options);
  130. if (Item.ConfigFile<>'') then
  131. L.Add('@'+Item.ConfigFile);
  132. L.Add(Item.FileName);
  133. C.Log.OnLog:=@DoCompilerLog;
  134. try
  135. C.Run(ParamStr(0),Item.BaseDir,L,True);
  136. Item.FSuccess:=True;
  137. except
  138. On E : Exception do
  139. Item.Output.Add(Format('Error %s compiling %s: %s',[E.ClassName,Item.FileName,E.Message]));
  140. end;
  141. FApp.ReportBuilt(Item);
  142. Finally
  143. C.Free;
  144. L.Free;
  145. end;
  146. Item.FThread:=Nil;
  147. end;
  148. { TCompiles }
  149. function TCompiles.GetC(AIndex : Integer): TCompileItem;
  150. begin
  151. Result:=Items[Aindex] as TCompileItem;
  152. end;
  153. { TCompileItem }
  154. function TCompileItem.GetOutput: TStrings;
  155. begin
  156. If (FOutput=Nil) then
  157. FOutput:=TStringList.Create;
  158. Result:=FOutput;
  159. end;
  160. function TCompileItem.GetOptions: TStrings;
  161. begin
  162. If (FOptions=Nil) then
  163. FOptions:=TStringList.Create;
  164. Result:=FOptions;
  165. end;
  166. destructor TCompileItem.Destroy;
  167. begin
  168. FreeAndNil(FOutput);
  169. FreeAndNil(FOptions);
  170. inherited Destroy;
  171. end;
  172. { TDirWatcher }
  173. procedure TDirWatcher.DoChange(Sender: TObject; aEntry: TDirectoryEntry; AEvents: TFileEvents);
  174. begin
  175. if Assigned(FApp) then
  176. FApp.AddToStatus(AEntry,AEvents);
  177. end;
  178. constructor TDirWatcher.Create(App: THTTPCompilerApplication; ADir: String);
  179. begin
  180. Inherited create(APP);
  181. FApp:=App;
  182. FDW:=TDirwatch.Create(Self);
  183. FDW.AddWatch(ADir,allEvents);
  184. FDW.OnChange:=@DoChange;
  185. TThread.ExecuteInThread(@FDW.StartWatch);
  186. end;
  187. destructor TDirWatcher.Destroy;
  188. begin
  189. FApp:=Nil;
  190. FDW.Terminate;
  191. FreeAndNil(FDW);
  192. inherited Destroy;
  193. end;
  194. { THTTPCompilerApplication }
  195. procedure THTTPCompilerApplication.DoLog(EventType: TEventType; const Msg: String);
  196. begin
  197. {AllowWriteln}
  198. if Quiet then
  199. exit;
  200. if IsConsole then
  201. Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz',Now),' [',EventType,'] ',Msg)
  202. else
  203. inherited DoLog(EventType, Msg);
  204. {AllowWriteln-}
  205. end;
  206. procedure THTTPCompilerApplication.Usage(Msg : String);
  207. begin
  208. {AllowWriteln}
  209. if (Msg<>'') then
  210. Writeln('Error: ',Msg);
  211. Writeln('Usage ',ExtractFileName(ParamStr(0)),' [options] ');
  212. Writeln('Where options is one or more of : ');
  213. Writeln('-d --directory=dir Base directory from which to serve files.');
  214. Writeln(' Default is current working directory: ',GetCurrentDir);
  215. Writeln('-h --help This help text');
  216. Writeln('-i --indexpage=name Directory index page to use (default: index.html)');
  217. Writeln('-n --noindexpage Do not allow index page.');
  218. Writeln('-p --port=NNNN TCP/IP port to listen on (default is 3000)');
  219. Writeln('-q --quiet Do not write diagnostic messages');
  220. Writeln('-w --watch Watch directory for changes');
  221. Writeln('-c --compile[=proj] Recompile project if pascal files change. Default project is app.lpr');
  222. Writeln('-s --simpleserver Only serve files, do not enable compilation.');
  223. Halt(Ord(Msg<>''));
  224. {AllowWriteln-}
  225. end;
  226. constructor THTTPCompilerApplication.Create(AOWner: TComponent);
  227. begin
  228. inherited Create(AOWner);
  229. FStatusLock:=TCriticalSection.Create;
  230. FStatusList:=TFPObjectList.Create(False);
  231. FCompiles:=TCompiles.Create(TCompileItem);
  232. end;
  233. destructor THTTPCompilerApplication.Destroy;
  234. begin
  235. FStatusLock.Enter;
  236. try
  237. FreeAndNil(FCompiles);
  238. FreeAndNil(FStatusList);
  239. finally
  240. FStatusLock.Leave;
  241. end;
  242. FreeAndNil(FStatusLock);
  243. inherited Destroy;
  244. end;
  245. procedure THTTPCompilerApplication.StartWatch(ADir : String);
  246. begin
  247. FDW:=TDirWatcher.Create(Self,ADir);
  248. end;
  249. procedure THTTPCompilerApplication.ReportBuilding(AItem: TCompileItem);
  250. Var
  251. O : TJSONObject;
  252. begin
  253. O:=TJSONObject.Create(['action','building','compileID',AItem.ID,'project',AItem.FileName,'config',AItem.ConfigFile]);
  254. AddToStatus(O);
  255. end;
  256. procedure THTTPCompilerApplication.ReportBuilt(AItem: TCompileItem);
  257. Var
  258. O : TJSONObject;
  259. A : TJSONArray;
  260. I : Integer;
  261. begin
  262. A:=TJSONArray.Create;
  263. For I:=0 to AItem.Output.Count-1 do
  264. A.Add(AItem.Output[i]);
  265. O:=TJSONObject.Create(['action','built','compileID',AItem.ID,'project',AItem.FileName,'config',AItem.ConfigFile,'output',A,'success',AItem.Success]);
  266. AddToStatus(O);
  267. end;
  268. procedure THTTPCompilerApplication.AddToStatus(O : TJSONObject);
  269. begin
  270. FStatusLock.Enter;
  271. try
  272. {$ifdef VerboseHTTPCompiler}
  273. Writeln('Adding to status ',Assigned(O),' : ',O.ClassName);
  274. {$endif}
  275. FStatusList.Add(O);
  276. finally
  277. FStatusLock.Leave;
  278. end;
  279. end;
  280. procedure THTTPCompilerApplication.AddToStatus(AEntry: TDirectoryEntry; AEvents: TFileEvents);
  281. Var
  282. O : TJSONObject;
  283. FN : String;
  284. begin
  285. Log(etDebug,'File change detected: %s (%s)',[AEntry.name,FileEventsToStr(AEvents)]);
  286. O:=TJSONObject.Create(['action','file','name',AEntry.name,'events',FileEventsToStr(AEvents)]);
  287. if Pos(ExtractFileExt(AEntry.Name),'.lpr.pas.pp.inc.dpr')>0 then
  288. FN:=AEntry.Name;
  289. if (FN<>'') then
  290. O.Add('recompile',true);
  291. AddToStatus(O);
  292. if (FN<>'') then
  293. begin
  294. Log(etDebug,'File change forces recompile: %s',[AEntry.name]);
  295. ScheduleCompile('',Nil);
  296. end;
  297. end;
  298. procedure THTTPCompilerApplication.DoStatusRequest(ARequest : TRequest; AResponse : TResponse);
  299. Var
  300. R,O : TJSONObject;
  301. A : TJSONArray;
  302. I : integer;
  303. begin
  304. Log(etDebug,'Status request from: %s',[ARequest.RemoteAddress]);
  305. R:=Nil;
  306. try
  307. FStatusLock.Enter;
  308. try
  309. if (FStatusList.Count=0) then
  310. R:=TJSONObject.Create(['ping',True])
  311. else
  312. begin
  313. {$ifdef VerboseHTTPCompiler}
  314. Writeln(FStatusList[0].ClassName);
  315. {$endif}
  316. O:=FStatusList[0] as TJSONObject;
  317. FStatusList.Delete(0);
  318. if O.Get('action','')<>'file' then
  319. R:=O
  320. else
  321. begin
  322. // If first event is file event, then add and delete all file events in list.
  323. A:=TJSONArray.Create([O]);
  324. O.Delete('action');
  325. R:=TJSONObject.Create(['action','sync','files',A]);
  326. For I:=FStatusList.Count-1 downto 0 do
  327. begin
  328. O:=FStatusList[I] as TJSONObject;
  329. if (O.Get('action','')='file') then
  330. begin
  331. A.Add(O);
  332. O.Delete('action');
  333. FStatusList.Delete(I);
  334. end;
  335. end;
  336. end
  337. end;
  338. finally
  339. FStatusLock.Leave;
  340. end;
  341. AResponse.ContentType:='application/json';
  342. AResponse.Content:=R.AsJSON;
  343. AResponse.SendResponse;
  344. finally
  345. R.Free;
  346. end;
  347. end;
  348. Function THTTPCompilerApplication.ScheduleCompile(const aProjectFile : String; Options : TStrings = Nil) : Integer;
  349. Var
  350. CI : TCompileItem;
  351. I,TC : Integer;
  352. begin
  353. TC:=0;
  354. For I:=0 to FCompiles.Count-1 do
  355. if Assigned(FCompiles[I].THread) then
  356. Inc(TC);
  357. if TC>10 then
  358. begin
  359. Log(etError,'Refusing compile of file "%s" using config file "%s"',[AProjectFile, ConfigFile]);
  360. Exit(nErrTooManyThreads);
  361. end;
  362. CI:=FCompiles.Add as TCompileItem;
  363. Log(etInfo,'Scheduling compile ID %d of file "%s" using config file "%s"',[CI.ID,AProjectFile, ConfigFile]);
  364. CI.BaseDir:=BaseDir;
  365. CI.FileName:=AProjectFile;
  366. CI.ConfigFile:=ConfigFile;
  367. if Assigned(Options) then
  368. CI.Options.Assign(Options);
  369. TCompileThread.Create(Self,CI);
  370. Result:=CI.ID;
  371. end;
  372. procedure THTTPCompilerApplication.DoRecompile(ARequest: TRequest; AResponse: TResponse);
  373. Var
  374. ID : Integer;
  375. PF,CL : String;
  376. Options: TStrings;
  377. begin
  378. PF:=ARequest.ContentFields.Values['ProjectFile'];
  379. CL:=ARequest.ContentFields.Values['CompileOptions'];
  380. if PF='' then
  381. PF:=ProjectFile;
  382. If (PF='') then
  383. begin
  384. AResponse.Code:=404;
  385. AResponse.CodeText:='No project file';
  386. AResponse.ContentType:='application/json';
  387. AResponse.Content:='{ "success" : false, "message": "no project file set or provided" }';
  388. end
  389. else
  390. begin
  391. Options:=Nil;
  392. try
  393. if CL<>'' then
  394. begin
  395. Options:=TStringList.Create;
  396. Options.Text:=Cl;
  397. end;
  398. ID:=ScheduleCompile(PF,Options);
  399. finally
  400. FreeAndNil(Options);
  401. end;
  402. if ID=nErrTooManyThreads then
  403. begin
  404. AResponse.Code:=403;
  405. AResponse.CodeText:='Too many compiles';
  406. AResponse.ContentType:='application/json';
  407. AResponse.Content:='{ "success" : false, "message": "Too many compiles running" }';
  408. end
  409. else
  410. begin
  411. AResponse.Code:=200;
  412. AResponse.ContentType:='application/json';
  413. AResponse.Content:=Format('{ "success" : true, "file": "%s", "commandLine" : "%s", "compileID": %d }',[StringToJSONString(PF),StringToJSONString(CL),ID]);
  414. end
  415. end;
  416. AResponse.SendResponse;
  417. end;
  418. Function THTTPCompilerApplication.HandleCompileOptions(aDir : String) : Boolean;
  419. begin
  420. Result:=False;
  421. Watch:=HasOption('w','watch');
  422. if Hasoption('P','project') then
  423. begin
  424. ProjectFile:=GetOptionValue('P','project');
  425. if ProjectFile='' then
  426. ProjectFile:=IncludeTrailingPathDelimiter(aDir)+'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(aDir);
  444. end;
  445. Result:=True;
  446. end;
  447. Function THTTPCompilerApplication.ProcessOptions : Boolean;
  448. Var
  449. S,IndexPage,D : String;
  450. begin
  451. Result:=False;
  452. S:=Checkoptions('shqd:ni:p:wP::c',['help','quiet','noindexpage','directory:','port:','indexpage:','watch','project::','config:','simpleserver']);
  453. if (S<>'') or HasOption('h','help') then
  454. usage(S);
  455. FServeOnly:=HasOption('s','serve-only');
  456. Quiet:=HasOption('q','quiet');
  457. Port:=StrToIntDef(GetOptionValue('p','port'),3000);
  458. D:=GetOptionValue('d','directory');
  459. if D='' then
  460. D:=GetCurrentDir;
  461. {$ifdef unix}
  462. MimeTypesFile:='/etc/mime.types';
  463. {$else}
  464. MimeTypesFile:=ExtractFilePath(System.ParamStr(0))+'mime.types';
  465. {$endif}
  466. FBaseDir:=D;
  467. if not ServeOnly then
  468. if not HandleCompileOptions(D) then
  469. exit(False);
  470. TSimpleFileModule.BaseDir:=IncludeTrailingPathDelimiter(D);
  471. TSimpleFileModule.OnLog:=@Log;
  472. Log(etInfo,'Listening on port %d, serving files from directory: %s',[Port,D]);
  473. if ServeOnly then
  474. Log(etInfo,'Compile requests will be ignored.');
  475. If not HasOption('n','noindexpage') then
  476. begin
  477. IndexPage:=GetOptionValue('i','indexpage');
  478. if (IndexPage='') then
  479. IndexPage:='index.html';
  480. Log(etInfo,'Using index page %s',[IndexPage]);
  481. TSimpleFileModule.IndexPageName:=IndexPage;
  482. end;
  483. Result:=True;
  484. end;
  485. procedure THTTPCompilerApplication.DoRun;
  486. begin
  487. If not ProcessOptions then
  488. begin
  489. Terminate;
  490. exit;
  491. end;
  492. if not ServeOnly then
  493. begin
  494. httprouter.RegisterRoute('$sys/compile',rmPost,@DoRecompile);
  495. httprouter.RegisterRoute('$sys/status',rmGet,@DoStatusRequest);
  496. end;
  497. TSimpleFileModule.RegisterDefaultRoute;
  498. inherited;
  499. end;
  500. end.