phar exclude directories when creating tar archive

1.7k Views Asked by At

I want to create a tar archive in a PHP script using the built-in PharData class.

I want the tar archive to represent a directory so I thought of using PharData::buildFromDirectory() to do that. Unfortunately the directory also is a git repository and has a .git folder in it which is much bigger than the directory itself.

So I need to remove that .git directory (ideally also the .idea directory...) from the archive because it would bloat it unnecessarily.

What I tried so far:

  • Using a regular expression to filter the directory out:

    $archive->buildFromDirectory("..", "@^(?!.git).+@");
    

    Which didn't work.

  • Using PharData::delete(), but unfortunately that seems to only delete a file and not a directory.

So, what is the best way to do what I want?

2

There are 2 best solutions below

0
On BEST ANSWER

The problem with your regex is that the full path of the file gets matched, not only the directory (basename). Thus you cannot filter out the .git directory itself.

Using a character class negation ([^.][^g][^i][^t]) does also not help because there are parts of the path that do match this regex, so the path matches anyway.

This means you can use positive matches only.


You could use Phar::buildFromIterator and then use RecursiveFilterIterator to filter out the files. There you can define your own matching method that filters correctly.

0
On

I've seen the following used to exclude git directories using a negative lookahead:

$phar->buildFromDirectory(__DIR__, '/^((?!\.git).)*$/');