简体   繁体   中英

Composer - PHP check if composer.json need update

Would like to ask, I made a simple php script to auto deploy from bitbucket when new set of code is being pushed to the repository which work fine. but from time to time there will be changes made to the composer.json file. So what I've done at this moment is by calling exec('composer update') every time the PHP script is being fired, which could be time consuming even though there are no changes made to the composer.json file.

Is there any way that I can call PHP to check if the composer.json file has been changed then only execute exec('composer update') ?

Is there any way that I can call PHP to check if the composer.json file has been changed then only execute exec('composer update') ?

I would suggest to do a history check of just one file from the repo by using "git diff" or compare/check the modification date of the file.

Examples:

  • git --no-pager diff --name-only HEAD~50 -- ./composer.json
    • check if composer.json was changed within the last 50 commits (HEAD)
  • git --no-pager diff --name-only origin/master~15 -- ./composer.json
    • check if composer.json was changed within the last 15 commits (master branch)

If the file name is returned, then the file was changed within the commit range.

You might need to change the number of commits the diff goes back in the history to look for a change, but here is a rough draft to get you started:

<?php

function fileChanged() {
    $cmd = 'git --no-pager diff --name-only HEAD~50 -- ./composer.json';
    exec($cmd, $output);
    return ($output[0] === 'composer.json') ? true : false;
}

if(fileChanged()) {
   exec('composer update');
} else {
   echo 'Found no change to "composer.json" with 50 commits. Skipping "composer update"';
}

Also for an auto-deployment pushing the composer.lock file to the repo and switching from running composer update to composer install could help, because Composer wouldn't need to do dependency resolution and version lookups, which improves deployment speed.

Running composer install will:

  • Check, if a composer.lock exists
    • If not, do a composer update to create it
  • If composer.lock exists, install the specified versions from the lock file

Running composer update will:

  • Check composer.json
  • Determine the latest versions to install based on your version specs
  • Install the latest versions
  • Update composer.lock to reflect the latest versions installed

Sidenote: I remember a similar or pretty close feature request ( --install-only-if-changed ) on the Github tracker: https://github.com/composer/composer/issues/3888 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM