Changeset - r27561:158cfd44fed7
[Not reviewed]
master
0 1 0
Rubidium - 17 months ago 2023-06-09 14:44:42
rubidium@openttd.org
Codechange: use std::string to find the executable's working directory
1 file changed with 19 insertions and 17 deletions:
0 comments (0 inline, 0 general)
src/fileio.cpp
Show inline comments
 
@@ -729,44 +729,46 @@ bool ExtractTar(const std::string &tar_f
 
extern void DetermineBasePaths(const char *exe);
 
#else /* defined(_WIN32) */
 

	
 
/**
 
 * Changes the working directory to the path of the give executable.
 
 * For OSX application bundles '.app' is the required extension of the bundle,
 
 * so when we crop the path to there, when can remove the name of the bundle
 
 * in the same way we remove the name from the executable name.
 
 * @param exe the path to the executable
 
 */
 
static bool ChangeWorkingDirectoryToExecutable(const char *exe)
 
{
 
	char tmp[MAX_PATH];
 
	strecpy(tmp, exe, lastof(tmp));
 

	
 
	bool success = false;
 
#ifdef WITH_COCOA
 
	char *app_bundle = strchr(tmp, '.');
 
	while (app_bundle != nullptr && !StrStartsWithIgnoreCase(app_bundle, ".app")) app_bundle = strchr(&app_bundle[1], '.');
 
	std::string path = exe;
 

	
 
	if (app_bundle != nullptr) *app_bundle = '\0';
 
#endif /* WITH_COCOA */
 
	char *s = strrchr(tmp, PATHSEPCHAR);
 
	if (s != nullptr) {
 
		*s = '\0';
 
		if (chdir(tmp) != 0) {
 
			Debug(misc, 0, "Directory with the binary does not exist?");
 
		} else {
 
			success = true;
 
#ifdef WITH_COCOA
 
	for (size_t pos = path.find_first_of('.'); pos != std::string::npos; pos = path.find_first_of('.', pos + 1)) {
 
		if (StrEqualsIgnoreCase(path.substr(pos, 4), ".app")) {
 
			path.erase(pos);
 
			break;
 
		}
 
	}
 
	return success;
 
#endif /* WITH_COCOA */
 

	
 
	size_t pos = path.find_last_of(PATHSEPCHAR);
 
	if (pos == std::string::npos) return false;
 

	
 
	path.erase(pos);
 

	
 
	if (chdir(path.c_str()) != 0) {
 
		Debug(misc, 0, "Directory with the binary does not exist?");
 
		return false;
 
	}
 

	
 
	return true;
 
}
 

	
 
/**
 
 * Whether we should scan the working directory.
 
 * It should not be scanned if it's the root or
 
 * the home directory as in both cases a big data
 
 * directory can cause huge amounts of unrelated
 
 * files scanned. Furthermore there are nearly no
 
 * use cases for the home/root directory to have
 
 * OpenTTD directories.
 
 * @return true if it should be scanned.
 
 */
0 comments (0 inline, 0 general)