Coder Social home page Coder Social logo

git.php's Introduction

Git.php

Description

A PHP git repository control library. Allows the running of any git command from a PHP class. Runs git commands using proc_open, not exec or the type, therefore it can run in PHP safe mode.

Requirements

A system with git installed

Basic Use

require __DIR__ . '/../vendor/autoload.php';

use Kbjr\Git\Git;

$repo = Git::open('/path/to/repo');  // -or- Git::create('/path/to/repo')

$repo->add('.');
$repo->commit('Some commit message');
$repo->push('origin', 'master');

Like my work?

ko-fi

git.php's People

Contributors

adrorocker avatar amalmurali47 avatar annulen avatar bentasker avatar bishoya avatar bmorg avatar eamelink avatar elliottlandsborough avatar fitorec avatar gartner avatar kbjr avatar maadhattah avatar robbat2 avatar sebastian-marinescu avatar squiddle avatar steveworley avatar syrusakbary avatar thelfensdrfer avatar tomasfejfar avatar uuf6429 avatar wangxiyu191 avatar werring avatar woolfg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

git.php's Issues

Add this library to Packagist please.

As the title says. Composer cannot automatically find/install without an entry on Packagist. Takes a few minutes to create a user account, then add the package.

Composer 2.0 package-name // Uppercase name will error

Summary

Composer 2.0 wants package-names to be lowercase

Step to reproduce

composer install on a server

Observed behavior

Throws a deprecation warning:

Deprecation warning: Your package name kbjr/Git.php is invalid, it should not contain uppercase characters. We suggest using kbjr/git.php instead. Make sure you fix this as Composer 2.0 will error.

Environment

Composer version 1.8.1 2019-01-29

Line 333 throws error on "config --get alias.example"

I'm writing a condition to ensure an alias is available and if its not it'll create the alias but running this code

$repo->run("config --get alias.example");

throws an empty error for line 333. Checking it myself $status = 1.

A similar command "status --short" which gives an empty response does not trigger this warning. Not sure whats going on here. Can you please look into this for me.

Thrown ConsoleException when git command returns nothing

I get a ConsoleException when I run below command.

$git->repo->run("config core.safecrlf false");

And it seems in general I get that exception when I run commands that run successfully however don't return with anything.

My stack trace points to line 100 of Console.php

if ($status) throw new ConsoleException($stderr . PHP_EOL . $stdout);

And honestly that condition looks very sketchy. Shouldn't the conditional statement be checking if $status returns -1? And why are we trimming the return value anyway?

Full function from Command.php below.

    public function runCommand($command)
    {
        $descriptorSpec = array(
            1 => array('pipe', 'w'),
            2 => array('pipe', 'w'),
        );
        $pipes = array();
        /**
         * Depending on the value of variables_order, $_ENV may be empty.
         * In that case, we have to explicitly set the new variables with
         * putenv, and call proc_open with env=null to inherit the reset
         * of the system.
         *
         * This is kind of crappy because we cannot easily restore just those
         * variables afterwards.
         *
         * If $_ENV is not empty, then we can just copy it and be done with it.
         */
        if (count($_ENV) === 0) {
            $env = NULL;
            foreach ($this->envopts as $k => $v) {
                putenv(sprintf("%s=%s", $k, $v));
            }
        } else {
            $env = array_merge($_ENV, $this->envopts);
        }
        $cwd = $this->currentPath;
        $resource = proc_open($command, $descriptorSpec, $pipes, $cwd, $env);

        $stdout = stream_get_contents($pipes[1]);
        $stderr = stream_get_contents($pipes[2]);
        foreach ($pipes as $pipe) {
            fclose($pipe);
        }

        $status = trim(proc_close($resource));
        if ($status) throw new ConsoleException($stderr . PHP_EOL . $stdout);

        return $stderr . $stdout;
    }
}

Bare Repo Creation

I can see the create_new() metthod creates a normal repo, but I guess creating a bare repo would make more sense.

Or at least have an alternative way to do that.

Host key verification failure

I am getting the error: "Message: Host key verification failed. fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists."

When I run exec('whoami') from within my PHP controller I get 'opcode' and when I cat /etc/password I see that this user's home directory is /var/www/vhost/domain.com so I created /var/www/vhost/domain.com/.ssh and copied my github SSH key into that directory. I chown'd that directory opcode:psacln to mtch my other web files, and set .ssh to chmod 0700 and my SSH key to 0600. When I run git remote -v I see my upstream github repo is correct.

Any ideas?

Array to string conversion

Notice: Array to string conversion in /Users/dovy/Development/Sites/builder.dev/public/wp-content/plugins/redux-builder/admin/Git.php on line 308

Fixed it by adding a @ to suppress the error... But any ideas?

Push where upstream branch does not exist

We are using this library to do auto-code commits from a Drupal implementation. When we build a site we pass a non-existent branch to the site which checks out the repositories locally to a branch which potentially does not exist on the remote.

When I get the error below, and try and manually do a git push git tells me I need to git push --set-upstream origin branchname, but looking at line 568 of Git.php I see there is no way to set-upstream in the library, and there is no way to create the branch on the remote.

WD php: Exception: in GitRepo->run_command() (line 280 of /var/.../libraries/git/Git.php). Cannot modify header information - headers already sent by (output started at /usr/share/php/drush/includes/output.inc:38) bootstrap.inc:1232 Exception: in GitRepo->run_command() (line 280 of /var/aegir/platforms/.../libraries/git/Git.php).

Pushing to github repo - 403 Forbidden access

How can I push to github repo?

I'm always getting this error: "Uncaught exception 'Exception' with message 'error: The requested URL returned error: 403 Forbidden while accessing https://github.com/zorandjukic/test.git/info/refs fatal"

$repo = Git::clone_remote(DIR.'/repo', 'https://github.com/zorandjukic/test.git');
$repo->setenv('username', 'zorandjukic');
$repo->setenv('password', 'mypassword');
$repo->add('.');
$repo->commit('Some commit message');
$repo->push('origin', 'master');

Could you help me with this problem?

Bypass of PHP issue

When my resulting command looks like

"C:\Program Files\Git\bin\git.exe" commit -av -m "Test commit"

I receive an error described here https://bugs.php.net/bug.php?id=49139

In the bottom of the page there is a bypass. Need to surround the resulting command with one more quotes like that

""C:\Program Files\Git\bin\git.exe" commit -av -m "Test commit""

$repo->add adds all the files of the repository

I want to add only one file for my commit not any other.
but when I do as following
$repo = Git::open($path_to_repository);
$repo->add($file_to_add);
$repo->commit($msg);

it added all the modified files to that commit.

How do I set up a sshkey Like this

Host key verification failed. fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

Library doesn't work on FreeBSD

/usr/bin/git would not normally exist on FreeBSD as it install non-system applications to /usr/local/bin

I'm assuming there is a more portable way to find the git executable then hardcoding the location? I can try finding a solution to this at somepoint but don't have a ton of time to look into it at the moment.

Thanks

PHP hanging indefinitely due to stream_get_contents

Reading from stream_get_contents on a stream that never gets output will hang PHP indefinitely. This is caused typically when output gets sent to STDERR instead of STDOUT.

In the case of Git commands this is happening to me on initial commit (git add .) when Git replaces LF with CRLF.

warning: LF will be replaced by CRLF in example.txt.
The file will have its original line endings in your working directory.

Unfortunately there is no current solution to this problem from the research I've read except to output to files via the shell command. More can be extensively read here where these folk have the same problem.

mikehaertl/php-shellcommand#20

For now I've turned off the warning I'm getting from Git with this config setting
git config core.safecrlf false

Git push doesn't return a message

Currently, $git->push doesn't return any message, which would allow me to check whether or not the push was successful and if not, why not.

Concurrent handle ?

Since a deploy system has concurrent question,then repo status will be mess。
A lock may needed。

It will be added in future?

thank you。

empty Exception thrown

Fatal error: Uncaught exception 'Exception' in /Users/emullins/www/local.apppress.com/includes/Git_php/Git.php:317

Any ideas? I'd guess it's failing when prompted for a pw on the git user? But when I try to use an ssh key or put the pw in the origin url in my config I get the same.

Fatal error: Uncaught exception 'Exception' with message 'error: unable to unlink

I have setup Git pull from web with this library and when i am trying to pull in server its says

Fatal error: Uncaught exception 'Exception' with message 'error: unable to unlink old 'xxxx.file' (Permission denied) fatal: Could not reset index file to revision 'FETCH_HEAD'. ' in Git.php:317 Stack trace: #0 Git.php(332): GitRepo->run_command('/usr/bin/git re...') #1 filename: GitRepo->run('reset --hard FE...') #2 filename(30): RunGit->doPull() #3 {main} thrown in Git.php on line 317

Git Pull/Push error

Hi,
I am just used your library for integrating git with php framework.
So i have one repo with ssh supports need to pull or push command from php itself.
But when i used command from linux framework it throws error as below,

Message: Could not create directory '/home/ampps/.ssh'.
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Here 'ampps' is my apache user.

Can you please help me out?
Thank you.

Authenticating a push?

Hi!
My use case is as follows: a user specifies a repo, a branch, their Git username and password. The script then does a clone of that repo, adds a file to it, makes a commit, and pushes it back to origin.

I'm now stuck on the "pushes it back to origin" part -- is there any way of authenticating other than setting up public key or digest authentication?

Thanks!

Cloning a remote repo

Hi!
How would I clone a remote repo?

$repo = Git::open('/Users/aendrew/Sites/github/test');

$repo->clone_remote('git://github.com/kbjr/Git.php.git');

Fails with:

Fatal error: Uncaught exception 'Exception' with message 'fatal: destination path '/Users/aendrew/Sites/github/test' already exists and is not an empty directory.
' in /Users/aendrew/Sites/github/Git.php/Git.php:242

If I try accessing it directly through the GitRepo class, I get the same error, but from the directory in which the script resides.

Might be worth moving the clone_remote method to the Git class?

fetch error

Plz help

my declaration :

require_once './Git_cls.php';

Git::windows_mode();
$repo = Git::open('C:\xampp\htdocs\SyncPHP');
$repo->fetch();

Error :

Fatal error: Uncaught Exception: bash: /dev/tty: No such device or address error: failed to execute prompt script (exit code 1) fatal: could not read Username for 'https://gteamvsc.visualstudio.com': No error in C:\xampp\htdocs\SyncPHP\Git.php:348 Stack trace: #0 C:\xampp\htdocs\SyncPHP\Git.php(364): GitRepo->run_command('git fetch') #1 C:\xampp\htdocs\SyncPHP\Git.php(625): GitRepo->run('fetch') #2 C:\xampp\htdocs\SyncPHP\index.php(7): GitRepo->fetch() #3 {main} thrown in C:\xampp\htdocs\SyncPHP\Git.php on line 348


**

but when i make command with cmd 'git fetch' directly in repo directory work fine

**

error

Fatal error: Uncaught exception 'Exception' with message '"\cakephp_test" does not exist' in C:\xampp\htdocs\Git.php-master\Git.php:234
Stack trace:
#0 C:\xampp\htdocs\Git.php-master\Git.php(180): GitRepo->set_repo_path('\cakephp_test', false, true) 
#1 C:\xampp\htdocs\Git.php-master\Git.php(83): GitRepo->__construct('\cakephp_test')
#2 C:\xampp\htdocs\Git.php-master\index.php(4): Git::open('\cakephp_test')
#3 {main} thrown in C:\xampp\htdocs\Git.php-master\Git.php on line 234

On commit not finding use.name nor user.email

Whenever I try to run the code to do a commit I get the following back from the run_command function:

/usr/bin/git commit -av -m 'sort(page): home by somebody'

*** Please tell me who you are.

Run

  git config --global user.email "[email protected]"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

I checked the path to the repo in $cwd is correct and running " git config --global user.email/user.name" and " git config user.email/user.name" return correct values.
Also it's strange that in the commit message says "sort" since I did an update (saved the page).

The environment variables are these:

PATH=/usr/bin:/bin:/usr/sbin:/sbin, XPC_SERVICE_NAME=0, XPC_FLAGS=0x80, XPC_SERVICES_UNAVAILABLE=1

I've run out of ideas but seems like "proc_open" is losing completely the context.
Have you experienced something similar? Do you have any debugging hints or an idea how to fix this?

mkdir(): Permission denied

Hi guys,

I get a:

  mkdir(): Permission denied

What might be the issue? I'm on an Ubuntu box with Nginx.

Thanks very much.

Does not work (even test) on Windows

Starting Git.php Test Suite.

Testing Git.
Git was located and tested successfully

Testing Git::create().
Error: Test case threw an exception:
  Systém nemůže nalézt uvedenou cestu.


Testing Git::create([ $source ]).
Error: Test case threw an exception:
  Systém nemůže nalézt uvedenou cestu.


Testing Git::open().
Error: Test case threw an exception:
  "W:\www\frameworks\Git.php\test/test.git" does not exist


------------------------------
Tests Complete. Results:
Errors: 3  Warnings: 0

Also fails for simple script like:

<?php
require_once 'Git.php/Git.php';

$path = getcwd() . '/';
echo $path;
$repo = Git::open($path);
echo $repo->active_branch();

run inside repo

c:\tmp>php rebuild_mo_git.php
c:\tmp
Fatal error: Uncaught exception 'Exception' with message 'Systém nemůže nalézt uvedenou cestu.
' in W:\www\frameworks\Git.php\Git.php:217
Stack trace:
#0 W:\www\frameworks\Git.php\Git.php(232): GitRepo->run_command('/usr/bin/git br...')
#1 W:\www\frameworks\Git.php\Git.php(351): GitRepo->run('branch')
#2 W:\www\frameworks\Git.php\Git.php(370): GitRepo->list_branches(true)
#3 c:\tmp\rebuild_mo_git.php(7): GitRepo->active_branch()
#4 {main}
  thrown in W:\www\frameworks\Git.php\Git.php on line 217

Seems like it fails to locate git.

c:\tmp>git --version
git version 1.7.9

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.