3

I am trying to build a simple deployer in Laravel, that will receive a webhook, perform a deployment and store some information (from the hook) about said deployment.

I am using Laravel 5.2 jobs dispatcher to perform the following:

public function deploy()
{
    $result = 0;
    $output = array();
    exec('cd ' . $this->deploymentMapping->full_file_path . '; git pull', $output, $result);
    return array(
        'result' => $result,
        'output' => $this->outputToString($output)
    );
}

My understanding of the exec() function is that this should not dump any errors directly, but will store them in $output.

However, when I run php artisan queue:work on my server in the command line, to test the job dispatcher, I just immediately get fatal: Not a git repository (or any of the parent directories): .git dumped into the command line output. This git error is correct, but it is making the job "fail" as though exec() threw an error. Is this correct? My job should be reporting the error in its own way, as follows:

public function handle()
{
    $deploymentAttempt = new DeploymentAttempt();
    $deploymentAttempt->deployment_id = $this->deploymentID;
    $gitResponse = $this->deployer->deploy(); //the above function
    $deploymentAttempt->success = !($gitResponse['result'] > 0);
    $deploymentAttempt->message = $gitResponse['output'];
    $deploymentAttempt->save();
}
k4kuz0
  • 1,045
  • 1
  • 10
  • 24

1 Answers1

2

This is because PHP's exec doesn't provide a simple way to capture the stderr output separately.

You need to capture the stderr too.

Redirecting stderr to stdout should do the trick. Append 2>&1 to the end of your command.

exec('cd ' . $this->deploymentMapping->full_file_path . '; git pull 2>&1', $output, $result);

It will fill the array $output with the expected output, one line per array key.

To know more about how 2>&1 works you can follow this thread.

Prashant Pokhriyal
  • 3,727
  • 4
  • 28
  • 40
  • Thanks! The error that was making the job fail wasn't actually this problem with StdOut/StdErr, it was actually me writing `$deploymentAttempt->success` rather than `$deploymentAttempt->successful`. I'm a dingus. Thanks for your help :) – k4kuz0 Oct 28 '17 at 20:14
  • Thanks man, this saved me hours of troubleshooting... – hiddeneyes02 Feb 12 '22 at 21:44