0

So I am currently working using a Unity project in a specific repository. How can I get the name of this repository I am working in? That is, the name of the folder directly above the .git folder.

The way I have done it is like so:

Directory.GetCurrentDirectory().GetParentDirectory().GetParentDirectory().GetParentDirectory().GetFilename();

However, this feels like not the best way to do it since it's almost like as if I am hard coding?

What other ways can I do this?

AaySquare
  • 123
  • 10
  • Is this specifically for the editor or do you need this name also at play time on end user's device? – Ruzihm Mar 02 '22 at 15:57
  • Specifically for the editor only as I want to display this repo directory name on an editor window. So not for during the play time at all. – AaySquare Mar 02 '22 at 17:25
  • 1
    Consider running `git rev-parse --git-dir` to locate the actual repository storage directory, or—probably better—`git rev-parse --show-toplevel` to find the top level of the working tree. Use these plus the current working directory to get the path you want. Git also has `--show-cdup` which will show the number of `../` operations required to climb to the top of the working tree. – torek Mar 03 '22 at 01:00
  • @torek I like this method and it worked. I used `git rev-parse --show-toplevel` specifically which gave me the repository path. After that I just did `.GetFilename()` on the path string and it gave me the repository name itself. – AaySquare Mar 03 '22 at 16:30

2 Answers2

2

You could probably start with a known folder like e.g. Application.dataPath which is the Assets folder and from there bubble up until you find the root

var directory = new DirectoryInfo(Application.dataPath);
while(directory.GetDirectories(".git").Length == 0)
{
    directory = directory.Parent;

    if(directory == null)
    {
        throw new DirectoryNotFoundException("We went all the way up to the system root directory and didn't find any \".git\" directory!");
    }
}
var repositoryPath = directory.FullName;
var repositoryName = directory.Name;

You could pobably also start at

var directory = new DirectoryInfo(System.Environment.CurrentDirectory);

which usually should be the root path of your project, so basically already one directory higher than the Assets.

derHugo
  • 83,094
  • 9
  • 75
  • 115
0

Assuming you mean the folder of your code when you run your game:

You can use AppDomain.CurrentDomain.BaseDirectory as stated in this question

MasterWil
  • 891
  • 8
  • 24
  • 2
    This returns the path of the Unity editor executable e.g. `C:\Program Files\Unity\Hub\Editor\2021.2.8f1\Editor` and is not quite what OP is looking for ;) – derHugo Mar 03 '22 at 16:07