File::getCurrentWorkingDirectory doesn't work when CWD is set from Xcode scheme options (OSX / posix)

Xcode allows to set the CWD from its scheme options, but it will just set the PWD environment variable, and if you set a custom directory there, and execute File::getCurrentWorkingDirectory it will return an empty File() because getcwd will return nullptr.

I’ve extended the function (for posix) to take into account the PWD env variable when getcwd fails:

File File::getCurrentWorkingDirectory()
{
    HeapBlock<char> heapBuffer;

    char localBuffer[1024];
    auto cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
    size_t bufferSize = 4096;

    while (cwd == nullptr && errno == ERANGE)
    {
        heapBuffer.malloc (bufferSize);
        cwd = getcwd (heapBuffer, bufferSize - 1);
        bufferSize += 1024;
    }

    if (cwd == nullptr)
        return File (CharPointer_UTF8 (getenv ("PWD")));

    return File (CharPointer_UTF8 (cwd));
}

Maybe this is something that could be fixed ?

There are cases where getcwd returning nullptr is the correct thing to do, like if the directory you are currently in has been deleted. Silently falling back to PWD after a long chain of chdirs would be very surprising.

Unfortunately I can’t think of an automatic way around this.

Yeah indeed, i’m experiencing a weird behaviour in Xcode where you override the CWD in the options for the binary, then when the app starts, getpwd returns nullptr and chdir consistently fails, so it’s impossible to get or set the CWD, and that one is only available in the PWD env variable. By default when you launch debugging from xcode without setting the cwd, the apps is set to start from /, so i wanted to change that to be able to be executed from a writable directory at least. Not sure how to workaround it tho

For this specific situation could you do if (getCurrentWorkingDirectory() == {}) setCurrentWorkingDirectory($PWD); on initialisation of your app?

It doesn’t work if i have PWD set from Xcode cwd option, as setCurrentWorkingDirectory uses chdir internally and that fails.

Maybe i can use a separate env var and not involve using the xcode option at all.

I’m having this problem still. getCurrentWorkingDirectory doesn’t return the appropriate location. How can I use your snippet to remedy this?

I opted for a specific environment variable, so my app can test it and set the working directory to that variable instead of using Xcode current directory, because that is preventing getCurrentWorkingDirectory and setAsCurrentWorkingDirectory to work:

    juce::File currentWorkingDirectory = juce::File(juce::SystemStats::getEnvironmentVariable("MYAPP_PWD", {}).trim());

    if (currentWorkingDirectory.isDirectory())
        currentWorkingDirectory.setAsCurrentWorkingDirectory();

Hope it helps