The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Git::Raw::Repository - Git repository class

VERSION

version 0.33

SYNOPSIS

    use Git::Raw;

    # clone a Git repository
    my $url  = 'git://github.com/ghedo/p5-Git-Raw.git';
    my $repo = Git::Raw::Repository -> clone($url, 'p5-Git-Raw', {
      'callbacks' => {
        'transfer_progress' => sub {
          my ($total_objects, $received_objects, $local_objects, $total_deltas,
            $indexed_deltas, $received_bytes) = @_;

          print "Objects: $received_objects/$total_objecs", "\n";
          print "Received: ", int($received_bytes/1024), "KB", "\n";
        }
      }
    });

    # print all the tags of the repository
    foreach my $tag ($repo -> tags) {
      say $tag -> name;
    }

DESCRIPTION

A Git::Raw::Repository represents a Git repository.

WARNING: The API of this module is unstable and may change without warning (any change will be appropriately documented in the changelog).

METHODS

init( $path, $is_bare )

Initialize a new repository at $path.

clone( $url, $path, \%opts )

Clone the repository at $url to $path. Valid fields for the %opts hash are:

  • "bare"

    If true (default is false) create a bare repository.

  • "remote_name"

    The name to be given to the "origin" remote (default is "origin").

  • "checkout_branch"

    The name of the branch to checkout (default is to use the remote's HEAD).

  • "ignore_cert_errors"

    If true (default is false) ignore errors validating the remote host's certificate.

  • "disable_checkout"

    If true (default is false) files will not be checked out after the clone completes.

  • "callbacks"

    • "credentials"

      The callback to be called any time authentication is required to connect to the remote repository. The callback receives a string containing the URL of the remote, and it must return a Git::Raw::Cred object.

    • "progress"

      Textual progress from the remote. Text send over the progress side-band will be passed to this function (this is the 'counting objects' output). The callback receives a string containing progress information.

    • "completion"

      Completion is called when different parts of the download process are done (currently unused).

    • "transfer_progress"

      During the download of new data, this will be regularly called with the current count of progress done by the indexer. The callback receives the following integers: total_objects, received_objects, local_objects, total_deltas, indexed_deltas and received_bytes.

    • "update_tips"

      Each time a reference is updated locally, this function will be called with information about it. The callback receives a string containing the name of the reference that was updated, and the two OID's "a" before and "b" after the update.

open( $path )

Open the repository at $path.

discover( $path )

Discover the path to the repository directory given a subdirectory.

new( )

Create a new repository with neither backends nor config object.

config( )

Retrieve the default Git::Raw::Config of the repository.

index( )

Retrieve the default Git::Raw::Index of the repository.

head( [$new_head] )

Retrieve the Git::Raw::Reference pointed by the HEAD of the repository. If the Git::Raw::Reference $new_head is passed, the HEAD of the repository will be changed to point to it.

lookup( $id )

Retrieve the object corresponding to $id.

checkout( $object, \%opts )

Updates the files in the index and working tree to match the content of $object. Valid fields for the %opts hash are:

  • "checkout_strategy"

    Hash representing the desired checkout strategy. Valid fields are:

    • "none"

      Dry-run checkout strategy. It doesn't make any changes, but checks for conflicts.

    • "force"

      Take any action to make the working directory match the target (pretty much the opposite of "none".

    • "safe"

      Make only modifications that will not lose changes (to be used in order to simulate git checkout.

    • "safe_create"

      Like "safe", but will also cause a file to be checked out if it is missing from the working directory even if it is not modified between the target and baseline (to be used in order to simulate git checkout-index and git clone).

    • "allow_conflicts"

      Apply safe updates even if there are conflicts.

    • "remove_untracked"

      Remove untracked files from the working directory.

    • "remove_ignored"

      Remove ignored files from the working directory.

    • "update_only"

      Only update files that already exists (files won't be created not deleted).

    • "dont_update_index"

      Do not write the updated files' info to the index.

    • "no_refresh"

      Do not reload the index and git attrs from disk before operations.

    • "skip_unmerged"

      Skip files with unmerged index entries, instead of treating them as conflicts.

  • "notify"

    Notification flags for the notify callback. A list of the following options:

    • "conflict"

      Notifies about conflicting paths.

    • "dirty"

      Notifies about file that don't need an update but no longer matches the baseline. Core git displays these files when checkout runs, but won't stop the checkout.

    • "updated"

      Notification on any file changed.

    • "untracked"

      Notification about untracked files.

    • "ignored"

      Notifies about ignored files.

    • "all"

      All of the above.

  • "callbacks"

    Hash containg progress and notification callbacks. Valid fields are:

    • "notify"

      This callback is called for each file matching one of the notify options selected. It runs before modifying any files on disk. This callback should return a non-zero value should the checkout be cancelled. The callback receives a string containing the path of the file path and an array reference containing the reason why.

    • "progress"

      The callback to be invoked as a file is checked out. The callback receives a string containing the path of the file path, an integer completed_steps and an integer total_steps.

  • "paths"

    An optional array representing the list of files thay should be checked out. If "paths" is not specified, all files will be checked out (default).

Example:

    $repo -> checkout($repo -> head -> target, {
      'checkout_strategy' => { 'safe'  => 1 },
      'notify'    => [ 'all' ],
      'callbacks' => {
         'notify' => sub {
           my ($path, $why) = @_;

           print "File: $path: ", join(' ', @$why), "\n";
         },
         'progress' => sub {
            my ($path, $completed_steps, $total_steps) = @_;

            print "File: $path", "\n" if defined ($path);
            print "Progress: $completed_steps/$total_steps", "\n";
         }
      },
      'paths' => [ 'myscript.pl' ]
    });

reset( $target, \%opts )

Reset the current HEAD to the given commit. Valid fields for the %opts hash are:

  • "type"

    Set the type of the reset to be performed. Valid values are: "soft" (the head will be moved to the commit), "mixed" (trigger a soft reset and replace the index with the content of the commit tree) or "hard" (trigger a "mixed" reset and the working directory will be replaced with the content of the index).

  • "paths"

    List of entries in the index to be updated from the target commit tree. This is particularly useful to implement "git reset HEAD -- file file" behaviour. Note, if this parameter is specified, a value of "mixed" will be used for "type" (setting "type" to "soft" or "hard" has no effect).

status( [$file, $file, ...] )

Retrieve the status of files in the index and/or working directory. This functions returns a hash reference with an entry for each $file, or all files if no file parameters are provided. Each <$file> entry has a list of "flags", which may include: "index_new", "index_modified", "index_deleted", "index_renamed", "worktree_new", "worktree_modified", "worktree_deleted", "worktree_renamed" and "ignored".

If $file has been renamed in either the index or worktree or both, $file will also have a corresponding entry "index" and/or "worktree", containing the previous filename "old_file".

Example:

    my $file_statuses = $repo -> status();
    while (my ($file, $status) = each %$file_statuses) {
      my $flags = $status -> {'flags'};
      print "File: $file: Status: ", join (' ', @$flags), "\n";

      if (grep { $_ eq 'index_renamed' } @$flags) {
        print "Index previous filename: ",
        $status -> {'index'} -> {'old_file'}, "\n";
      }

      if (grep { $_ eq 'worktree_renamed' } @$flags) {
        print "Worktree previous filename: ",
        $status -> {'worktree'} -> {'old_file'}, "\n";
      }
    }

merge_base( @objects )

Find the merge base between @objects. Each element in @objects should either be a Git::Raw::Reference or a Git::Raw::Commit. A minimum of 2 objects should be provided.

merge_analysis( $reference )

Analyzes the given $reference and determines the opportunities for merging them into the HEAD of the repository. This function returns an array reference with optional members "normal", "up_to_date", "fast_forward" and/or "unborn".

  • "normal"

    A "normal" merge. Both HEAD and the given merge input have diverged from their common ancestor. The divergent commits must be merged.

  • "up_to_date"

    All given merge inputs are reachable from HEAD, meaning the repository is up-to-date and no merge needs to be performed.

  • "fast_forward"

    The given merge input is a fast-forward from HEAD and no merge needs to be performed. Instead, the given merge input may be checked out.

  • "unborn"

    The HEAD of the current repository is "unborn" and does not point to a valid commit. No merge can be performed, but the caller may wish to simply set HEAD to the target commit(s).

merge( $ref, [\%merge_opts, \%checkout_opts])

Merge the given $ref into HEAD. This function returns a hash reference with members "up_to_date", "fast_forward" and "id" if the merge was fast-forward. See Git::Raw::Repository->checkout() for valid %checkout_opts values. Valid fields for %merge_opts are

  • "flags"

    An array of flags for the tree, including:

    • "find_renames"

      Detect renames.

  • "favor"

    Specify content automerging behaviour. Valid values are "ours", "theirs", and "union".

  • "rename_threshold"

    Similarity metric for considering a file renamed (default is 50).

  • "target_limit"

    Maximum similarity sources to examine (overrides the "merge.renameLimit" configuration entry) (default is 200).

Example:

    my $branch = Git::Raw::Branch -> lookup($repo, 'branch', 1);
    my $analysis = $repo -> merge_analysis($branch);
    $repo -> merge($branch1,
     {
        'favor' => 'theirs'
     },

     {
      'checkout_strategy' => {
        'force' => 1
      }
     }
    );

ignore( $rules )

Add an ignore rules to the repository. The format of the rules is the same one of the .gitignore file (see the gitignore(5) manpage). Example:

    $repo -> ignore("*.o\n");

path_is_ignored( $path )

Checks the ignore rules to see if they would apply to the given file. This indicates if the file would be ignored regardless of whether the file is already in the index or committed to the repository.

diff( [\%opts] )

Compute the Git::Raw::Diff between the repo's default index and another tree. Valid fields for the %opts hash are:

  • "tree"

    If provided, the diff is computed between "tree" and the repo's default index. The default is the repo's working directory.

  • "flags"

    Flags for generating the diff. Valid values include:

    • "reverse"

      Reverse the sides of the diff.

    • "include_ignored"

      Include ignored files in the diff.

    • "recurse_ignored_dirs"

      Even if "include_ignored" is specified, an entire ignored directory will be marked with only a single entry in the diff. This flag adds all files under the directory as ignored entries, too.

    • "include_untracked"

      Include untracked files in the diff.

    • "recurse_untracked_dirs"

      Even if "include_untracked" is specified, an entire untracked directory will be marked with only a single entry in the diff (core git behaviour). This flag adds all files under untracked directories as untracked entries, too.

    • "ignore_filemode"

      Ignore file mode changes.

    • "ignore_submodules"

      Treat all submodules as unmodified.

    • "ignore_whitespace"

      Ignore all whitespace.

    • "ignore_whitespace_change"

      Ignore changes in amount of whitespace.

    • "ignore_whitespace_eol"

      Ignore whitespace at end of line.

    • "patience"

      Use the "patience diff" algorithm.

    • "minimal"

      Take extra time to find minimal diff.

  • "prefix"

    • "a"

      The virtual "directory" to prefix to old file names in hunk headers. (Default is L"a".)

    • "b"

      The virtual "directory" to prefix to new file names in hunk headers. (Default is L"b".)

  • "context_lines"

    The number of unchanged lines that define the boundary of a hunk (and to display before and after)

  • "interhunk_lines"

    The maximum number of unchanged lines between hunk boundaries before the hunks will be merged into a one.

  • "paths"

    A list of paths to constrain diff.

blob( $buffer )

Create a new Git::Raw::Blob. Shortcut for Git::Raw::Blob->create().

branch( $name, $target )

Create a new Git::Raw::Branch. Shortcut for Git::Raw::Branch->create().

branches( )

Retrieve a list of Git::Raw::Branch objects.

commit( $msg, $author, $committer, [@parents], $tree [, $update_ref ] )

Create a new Git::Raw::Commit. Shortcut for Git::Raw::Commit->create().

tag( $name, $msg, $tagger, $target )

Create a new Git::Raw::Tag. Shortcut for Git::Raw::Tag->create().

tags( )

Retrieve the list of Git::Raw::Tag objects representing the repository's annotated Git tags. Lightweight tags are not returned.

stash( $stasher, $msg )

Save the local modifications to a new stash. Shortcut for Git::Raw::Stash->save().

remotes( )

Retrieve the list of Git::Raw::Remote objects.

refs( )

Retrieve the list of Git::Raw::Reference objects.

walker( )

Create a new Git::Raw::Walker. Shortcut for Git::Raw::Walker->create().

path( )

Retrieve the complete path of the repository.

workdir( [$new_dir] )

Retrieve the working directory of the repository. If $new_dir is passed, the working directory of the repository will be set to the directory.

blame( $path )

Retrieve blame information for $path. Returns a Git::Raw::Blame object.

state( )

Determine the state of the repository. One of the following values is returned:

  • "none"

    Normal state

  • "merge"

    Repository is in a merge.

  • "revert"

    Repository is in a revert.

  • "cherry_pick"

    Repository is in a cherry-pick.

  • "bisect"

    Repository is bisecting.

  • "rebase"

    Repository is rebasing.

  • "rebase_interactive"

    Repository is in an interactive rebase.

  • "rebase_merge"

    Repository is in an rebase merge.

  • "apply_mailbox"

    Repository is applying patches.

  • "mailbox_or_rebase"

    Repository is applying patches or rebasing.

state_cleanup( )

Remove all the metadata associated with an ongoing command like merge, revert, cherry-pick, etc.

is_empty( )

Check if the repository is empty.

is_bare( )

Check if the repository is bare.

is_shallow( )

Check if the repository is a shallow clone.

AUTHOR

Alessandro Ghedini <alexbio@cpan.org>

LICENSE AND COPYRIGHT

Copyright 2012 Alessandro Ghedini.

This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.