Search code examples
delphidelphi-7

Detect build errors when launching Delphi compiler (dcc32.exe) from the command line


Our Delphi project can be built directly from the IDE, of course. But launching from the command line allows the process of building multiple projects to be automated. We are using:

ShellExecute(0,
    'open',
    PChar('[PATH-TO-DELPHI]\Bin\DCC32.EXE'),
    PChar('-B [PATH-TO-PROJECT]\MyProject.dpr'),
    PChar('[PATH-TO-PROJECT]'),
    SW_HIDE);

Normally this works great when there are no code or build errors, and ShellExecute returns a value of "42". However, if there are build errors, the return value is still "42".

You could build the project in the IDE to find the error(s). But is it possible to detect compilation errors from the command line, or to check some file or log to see if the build was successful or not?


Solution

  • Here's a procedure that waits for the process to finish and returns the exit code (0 for success, non-zero for failure):

    uses
      Winapi.ShellAPI;
    
    function RunAndWait(hWnd: HWND; filename: string; Parameters: string; var ProcExitCode: Cardinal): Boolean;
    var
      sei: TShellExecuteInfo;
    begin
      ZeroMemory(@sei, SizeOf(sei));
      sei.cbSize := SizeOf(TShellExecuteInfo);
      sei.Wnd := hwnd;
      sei.fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_NOASYNC or SEE_MASK_FLAG_NO_UI;
      sei.lpVerb := PChar('open');
      sei.lpFile := PChar(Filename);
      if parameters <> '' then
        sei.lpParameters := PChar(parameters);
      sei.nShow := SW_SHOWNORMAL;
    
      Result := ShellExecuteEx(@sei);
      try
        WaitForSingleObject(sei.hProcess, INFINITE);
    
        // If ShellExecuteEx succeeded, then get the exit code of the process we ran
        if Result then
          if not GetExitCodeProcess(sei.hProcess, ProcExitCode) then
            raise Exception.Create('Error ' + IntToStr(GetLastError) + ' during GetExitCodeProcess call');
    
      finally
        CloseHandle(sei.hProcess);
      end;
    end;