void AbstractGeneratorConfig::configureLogging() { if (getString("application.output-type") != "socket") { // log-path File logPath(getString("application.log-path")); if (logPath.exists()) { logPath.remove(true); } File logDir(Path(getString("application.log-path")).parent()); logDir.createDirectories(); // create the formatting file channel Formatter* simpleFileFormatter = new PatternFormatter("%t"); _loggerFormattersPool.add(simpleFileFormatter); Channel* simpleFileChannel = new SimpleFileChannel(getString("application.log-path")); _loggerChannelsPool.add(simpleFileChannel); Channel* formattingChannel = new FormattingChannel(simpleFileFormatter, simpleFileChannel); _loggerChannelsPool.add(formattingChannel); // configure the formatting file channel Logger::root().setChannel(formattingChannel); _logger.setChannel(formattingChannel); } }
void InitLog(_In_ TCHAR const * pluginDataPath) { tstring logPath(pluginDataPath); logPath.append(TEXT("\\LolSceneSwitch.log")); ofs.open(logPath, std::ofstream::out | std::ofstream::trunc); }
TrampolineMgr::TrampolineMgr(int entries) : m_nNext(0) { assert(m_pInstance == 0); m_pInstance = this; int ps = getpagesize(); void* mem; int bytes = entries * sizeof(Trampoline); bytes = (bytes + ps - 1) / ps * ps; mem = ::mmap(0, bytes, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if (mem == MAP_FAILED) throw std::runtime_error("Failed to map pages for TrampolineMgr"); m_pMem = static_cast<Trampoline*>(mem); m_nMax = bytes / sizeof(Trampoline); if (char* p = get_current_dir_name()) { m_wd = p; free(p); } ::gettimeofday(&m_startup, nullptr); std::cout << logPath() << std::endl; }
bool Application::InitFileSystem() { ///set working directory to where the binary is. auto workingDirectory = GetContext().GetFileSystem()->GetWorkingDirectory(); GetContext().GetFileSystem()->SetWriteDirectory(workingDirectory); ///create directory for application auto applicationDirectory = Path(GetApplicationId()); if (!GetContext().GetFileSystem()->CreateDirectory(applicationDirectory)) { printf("%s\n", "Failed to create directory for current application."); exit(-1); } Path appendedPath = Path(workingDirectory).append(applicationDirectory.generic_string()); GetContext().GetFileSystem()->SetWriteDirectory(appendedPath); GetContext().GetFileSystem()->AddSearchDirectory(appendedPath); auto & fileSystemVars = GetContext().GetApplicationSettingsManager()->GetGroup("filesystem"); Path logPath(fileSystemVars.GetVar("log_path").ValueS()); Path configPath(fileSystemVars.GetVar("config_path").ValueS()); GetContext().GetFileSystem()->CreateDirectory(logPath); GetContext().GetFileSystem()->CreateDirectory(configPath); return true; }
void readyLog(std::ofstream &stream) { time_t timer; char buffer[120]; std::string logPath("C:\\short_adr\\ArLog\\"); time(&timer); strftime(buffer, 80, "LOG-%d-%m-%Y__%I-%M-%S.txt", localtime(&timer)); logPath = logPath + buffer; std::cout << logPath << std::endl; stream.open(logPath.c_str()); stream << "file name : " << logPath << std::endl; }
void CPS2VM::ResetVM() { m_ee->Reset(); m_iop->Reset(); m_iop->SetBios(m_iopOs); //LoadBIOS(); if(m_ee->m_gs != NULL) { m_ee->m_gs->Reset(); } m_iopOs->Reset(new Iop::CSifManPs2(m_ee->m_sif, m_ee->m_ram, m_iop->m_ram)); CDROM0_Reset(); m_iopOs->GetIoman()->RegisterDevice("host", Iop::CIoman::DevicePtr(new Iop::Ioman::CDirectoryDevice(PREF_PS2_HOST_DIRECTORY))); m_iopOs->GetIoman()->RegisterDevice("mc0", Iop::CIoman::DevicePtr(new Iop::Ioman::CDirectoryDevice(PREF_PS2_MC0_DIRECTORY))); m_iopOs->GetIoman()->RegisterDevice("mc1", Iop::CIoman::DevicePtr(new Iop::Ioman::CDirectoryDevice(PREF_PS2_MC1_DIRECTORY))); m_iopOs->GetIoman()->RegisterDevice("cdrom0", Iop::CIoman::DevicePtr(new Iop::Ioman::CIsoDevice(m_pCDROM0))); m_iopOs->GetLoadcore()->SetLoadExecutableHandler(std::bind(&CPS2OS::LoadExecutable, m_ee->m_os, std::placeholders::_1, std::placeholders::_2)); m_iopOs->GetCdvdfsv()->SetReadToEeRamHandler(std::bind(&CPS2VM::ReadToEeRam, this, std::placeholders::_1, std::placeholders::_2)); m_vblankTicks = ONSCREEN_TICKS; m_inVblank = false; m_eeExecutionTicks = 0; m_iopExecutionTicks = 0; m_spuUpdateTicks = SPU_UPDATE_TICKS; m_currentSpuBlock = 0; RegisterModulesInPadHandler(); #ifdef DEBUGGER_INCLUDED try { boost::filesystem::path logPath(VPU_LOG_BASE); boost::filesystem::remove_all(logPath); boost::filesystem::create_directory(logPath); } catch(...) { } #endif }
bool Application::LoadConfig() { auto & fileSystemVars = GetContext().GetApplicationSettingsManager()->GetGroup("filesystem"); Path logPath(fileSystemVars.GetVar("log_path").ValueS()); Path configPath(fileSystemVars.GetVar("config_path").ValueS()); ///REFACTOR: Magic strings Path configFilePath = configPath; configFilePath.append("config.cfg"); if (!GetContext().GetApplicationSettingsManager()->LoadSettings(configFilePath)) GetContext().GetApplicationSettingsManager()->WriteSettings(configFilePath); return true; }
std::ostream* TrampolineMgr::getLogger() { if (g_loggerForPid == getpid()) return g_logger ? g_logger : &std::cerr; else { delete g_logger; g_logger = new std::ofstream(logPath(), std::ios_base::out | std::ios_base::app); if (!g_logger->is_open()) { delete g_logger; g_logger = 0; } g_loggerForPid = getpid(); return g_logger; } }
Credential::Credential(): _cRef(1), _pCredProvCredentialEvents(NULL) { DllAddRef(); ZeroMemory(_rgCredProvFieldDescriptors, sizeof(_rgCredProvFieldDescriptors)); ZeroMemory(_rgFieldStatePairs, sizeof(_rgFieldStatePairs)); ZeroMemory(_rgFieldStrings, sizeof(_rgFieldStrings)); // build the path to the log file based on this dll's name wchar_t* pwszDllPath = new wchar_t[260]; GetModuleFileName(HINST_THISDLL, pwszDllPath, 260); std::wstring logPath(pwszDllPath); delete[]pwszDllPath; logPath.replace(logPath.end()-3,logPath.end(),L"log"); debug = std::wofstream(logPath); }
static void logMessageHandler(QtMsgType type, const QMessageLogContext &, const QString &msg) { QString logPath(LibraryInfo::logPath() + "/qmh-log"); switch(type) { case QtDebugMsg: case QtWarningMsg: logPath += "-debug.log"; break; default: logPath += "-error.log"; break; } QFile logFile(logPath); logFile.open(QIODevice::WriteOnly); logFile.write(msg.toLatin1()); logFile.close(); }
void ImportFunction::_setFromParametersMap(const ParametersMap& map) { // Import RegistryKeyType importId(map.get<RegistryKeyType>(PARAMETER_IMPORT_ID)); try { boost::shared_ptr<const Import> import(ImportTableSync::Get(importId, *_env)); if(!import->get<DataSource>()) { throw RequestException("The id system of the specified import is not defined."); } // Log path bool outputLogs(map.getDefault<bool>(PARAMETER_OUTPUT_LOGS, false)); // Min log force ImportLogLevel minLogLevel(import->get<MinLogLevel>()); if(map.isDefined(PARAMETER_MIN_LOG_LEVEL)) { minLogLevel = static_cast<ImportLogLevel>(map.get<int>(PARAMETER_MIN_LOG_LEVEL)); } // Log path force string logPath(import->get<LogPath>()); if(map.isDefined(PARAMETER_LOG_PATH)) { logPath = map.get<string>(PARAMETER_LOG_PATH); } // Logger generation if(outputLogs) { // Importer generation _importer = import->getImporter( *_env, minLogLevel, logPath, _output, _result ); } else { // Importer generation _importer = import->getImporter( *_env, minLogLevel, logPath, optional<ostream&>(), _result ); } _importer->setFromParametersMap(map, true); _doImport = map.isTrue(PARAMETER_DO_IMPORT); _importDone = _importer->beforeParsing(); _importDone &= _importer->parseFiles(); _importDone &=_importer->afterParsing(); } catch(ObjectNotFoundException<DataSource> e) { throw RequestException("Datasource not found"); } catch(Exception e) { throw RequestException("Load failed : " + e.getMessage()); } }
int main(int argc, char** argv) { #ifdef OS_Darwin struct rlimit rlp; if (getrlimit(RLIMIT_NOFILE, &rlp) == 0) { if (rlp.rlim_cur < 1000) { rlp.rlim_cur = 1000; setrlimit(RLIMIT_NOFILE, &rlp); } } #endif { pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_getstacksize(&attr, &defaultStackSize); pthread_attr_destroy(&attr); if (defaultStackSize < 1024 * 1024 * 4) { // 4 megs should be enough for everyone right? defaultStackSize = 1024 * 1024 * 4; } } Rct::findExecutablePath(*argv); struct option opts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, 2 }, { "include-path", required_argument, 0, 'I' }, { "isystem", required_argument, 0, 's' }, { "define", required_argument, 0, 'D' }, { "log-file", required_argument, 0, 'L' }, { "setenv", required_argument, 0, 'e' }, { "no-Wall", no_argument, 0, 'W' }, { "Weverything", no_argument, 0, 'u' }, { "cache-AST", required_argument, 0, 'A' }, { "verbose", no_argument, 0, 'v' }, { "job-count", required_argument, 0, 'j' }, { "header-error-job-count", required_argument, 0, 'H' }, { "test", required_argument, 0, 't' }, { "test-timeout", required_argument, 0, 'z' }, { "clean-slate", no_argument, 0, 'C' }, { "disable-sighandler", no_argument, 0, 'x' }, { "silent", no_argument, 0, 'S' }, { "exclude-filter", required_argument, 0, 'X' }, { "socket-file", required_argument, 0, 'n' }, { "config", required_argument, 0, 'c' }, { "no-rc", no_argument, 0, 'N' }, { "data-dir", required_argument, 0, 'd' }, { "ignore-printf-fixits", no_argument, 0, 'F' }, { "no-unlimited-errors", no_argument, 0, 'f' }, { "block-argument", required_argument, 0, 'G' }, { "no-spell-checking", no_argument, 0, 'l' }, { "large-by-value-copy", required_argument, 0, 'r' }, { "disallow-multiple-sources", no_argument, 0, 'm' }, { "no-startup-project", no_argument, 0, 'o' }, { "no-no-unknown-warnings-option", no_argument, 0, 'Y' }, { "ignore-compiler", required_argument, 0, 'b' }, { "watch-system-paths", no_argument, 0, 'w' }, { "rp-visit-file-timeout", required_argument, 0, 'Z' }, { "rp-indexer-message-timeout", required_argument, 0, 'T' }, { "rp-connect-timeout", required_argument, 0, 'O' }, { "rp-connect-attempts", required_argument, 0, 3 }, { "rp-nice-value", required_argument, 0, 'a' }, { "thread-stack-size", required_argument, 0, 'k' }, { "suspend-rp-on-crash", no_argument, 0, 'q' }, { "rp-log-to-syslog", no_argument, 0, 7 }, { "start-suspended", no_argument, 0, 'Q' }, { "separate-debug-and-release", no_argument, 0, 'E' }, { "max-crash-count", required_argument, 0, 'K' }, { "completion-cache-size", required_argument, 0, 'i' }, { "completion-no-filter", no_argument, 0, 8 }, { "extra-compilers", required_argument, 0, 'U' }, { "allow-Wpedantic", no_argument, 0, 'P' }, { "enable-compiler-manager", no_argument, 0, 'R' }, { "enable-NDEBUG", no_argument, 0, 'g' }, { "progress", no_argument, 0, 'p' }, { "max-file-map-cache-size", required_argument, 0, 'y' }, #ifdef OS_FreeBSD { "filemanager-watch", no_argument, 0, 'M' }, #else { "no-filemanager-watch", no_argument, 0, 'M' }, #endif { "no-file-lock", no_argument, 0, 13 }, { "pch-enabled", no_argument, 0, 14 }, { "no-filesystem-watcher", no_argument, 0, 'B' }, { "arg-transform", required_argument, 0, 'V' }, { "no-comments", no_argument, 0, 1 }, #ifdef OS_Darwin { "launchd", no_argument, 0, 4 }, #endif { "inactivity-timeout", required_argument, 0, 5 }, { "daemon", no_argument, 0, 6 }, { "log-file-log-level", required_argument, 0, 9 }, { "watch-sources-only", no_argument, 0, 10 }, { "debug-locations", no_argument, 0, 11 }, { "tcp-port", required_argument, 0, 12 }, { 0, 0, 0, 0 } }; const String shortOptions = Rct::shortOptions(opts); if (getenv("RTAGS_DUMP_UNUSED")) { String unused; for (int i=0; i<26; ++i) { if (!shortOptions.contains('a' + i)) unused.append('a' + i); if (!shortOptions.contains('A' + i)) unused.append('A' + i); } printf("Unused: %s\n", unused.constData()); for (int i=0; opts[i].name; ++i) { if (opts[i].name) { if (!opts[i].val) { printf("No shortoption for %s\n", opts[i].name); } else if (opts[i].name[0] != opts[i].val) { printf("Not ideal option for %s|%c\n", opts[i].name, opts[i].val); } } } return 0; } bool daemon = false; List<String> argCopy; List<char*> argList; { bool norc = false; Path rcfile = Path::home() + ".rdmrc"; opterr = 0; StackBuffer<128, char*> originalArgv(argc); memcpy(originalArgv, argv, sizeof(char*) * argc); /* getopt will molest argv by moving pointers around when it sees * fit. Their idea of an optional argument is different from ours so we * have to take a copy of argv before they get their sticky fingers all * over it. * * We think this should be okay for an optional argument: * -s something * * They only populate optarg if you do: * -ssomething. * * We don't want to copy argv into argList before processing rc files * since command line args should take precedence over things in rc * files. * */ while (true) { const int c = getopt_long(argc, argv, shortOptions.constData(), opts, 0); if (c == -1) break; switch (c) { case 'N': norc = true; break; case 'c': rcfile = optarg; break; default: break; } } opterr = 1; argList.append(argv[0]); if (!norc) { String rc = Path("/etc/rdmrc").readAll(); if (!rc.isEmpty()) { for (const String& s : rc.split('\n')) { if (!s.isEmpty() && !s.startsWith('#')) argCopy += s.split(' '); } } if (!rcfile.isEmpty()) { rc = rcfile.readAll(); if (!rc.isEmpty()) { for (const String& s : rc.split('\n')) { if (!s.isEmpty() && !s.startsWith('#')) argCopy += s.split(' '); } } } const int s = argCopy.size(); for (int i=0; i<s; ++i) { String &arg = argCopy.at(i); if (!arg.isEmpty()) argList.append(arg.data()); } } for (int i=1; i<argc; ++i) argList.append(originalArgv[i]); optind = 1; } Server::Options serverOpts; serverOpts.threadStackSize = defaultStackSize; serverOpts.socketFile = String::format<128>("%s.rdm", Path::home().constData()); serverOpts.jobCount = std::max(2, ThreadPool::idealThreadCount()); serverOpts.headerErrorJobCount = -1; serverOpts.rpVisitFileTimeout = DEFAULT_RP_VISITFILE_TIMEOUT; serverOpts.rpIndexDataMessageTimeout = DEFAULT_RP_INDEXER_MESSAGE_TIMEOUT; serverOpts.rpConnectTimeout = DEFAULT_RP_CONNECT_TIMEOUT; serverOpts.rpConnectAttempts = DEFAULT_RP_CONNECT_ATTEMPTS; serverOpts.maxFileMapScopeCacheSize = DEFAULT_RDM_MAX_FILE_MAP_CACHE_SIZE; serverOpts.rpNiceValue = INT_MIN; serverOpts.options = Server::Wall|Server::SpellChecking; serverOpts.maxCrashCount = DEFAULT_MAX_CRASH_COUNT; serverOpts.completionCacheSize = DEFAULT_COMPLETION_CACHE_SIZE; #ifdef OS_FreeBSD serverOpts.options |= Server::NoFileManagerWatch; #endif // #ifndef NDEBUG // serverOpts.options |= Server::SuspendRPOnCrash; // #endif serverOpts.excludeFilters = String(EXCLUDEFILTER_DEFAULT).split(';'); serverOpts.dataDir = String::format<128>("%s.rtags", Path::home().constData()); const char *logFile = 0; Flags<LogFileFlag> logFlags = DontRotate; LogLevel logLevel(LogLevel::Error); LogLevel logFileLogLevel(LogLevel::Error); bool sigHandler = true; assert(Path::home().endsWith('/')); int argCount = argList.size(); char **args = argList.data(); bool defaultDataDir = true; int inactivityTimeout = 0; while (true) { const int c = getopt_long(argCount, args, shortOptions.constData(), opts, 0); if (c == -1) break; switch (c) { case 'N': case 'c': // ignored break; case 'S': logLevel = LogLevel::None; break; case 'X': serverOpts.excludeFilters += String(optarg).split(';'); break; case 'G': serverOpts.blockedArguments << optarg; break; case 1: serverOpts.options |= Server::NoComments; break; case 10: serverOpts.options |= Server::WatchSourcesOnly; break; case 11: if (!strcmp(optarg, "clear") || !strcmp(optarg, "none")) { serverOpts.debugLocations.clear(); } else { serverOpts.debugLocations << optarg; } break; case 12: serverOpts.tcpPort = atoi(optarg); if (!serverOpts.tcpPort) { fprintf(stderr, "Invalid port %s for --tcp-port\n", optarg); return 1; } break; case 13: serverOpts.options |= Server::NoFileLock; break; case 14: serverOpts.options |= Server::PCHEnabled; break; case 2: fprintf(stdout, "%s\n", RTags::versionString().constData()); return 0; case 6: daemon = true; logLevel = LogLevel::None; break; case 9: if (!strcasecmp(optarg, "verbose-debug")) { logFileLogLevel = LogLevel::VerboseDebug; } else if (!strcasecmp(optarg, "debug")) { logFileLogLevel = LogLevel::Debug; } else if (!strcasecmp(optarg, "warning")) { logFileLogLevel = LogLevel::Warning; } else if (!strcasecmp(optarg, "error")) { logFileLogLevel = LogLevel::Error; } else { fprintf(stderr, "Unknown log level: %s options are error, warning, debug or verbose-debug\n", optarg); return 1; } break; case 'U': serverOpts.extraCompilers.append(std::regex(optarg)); break; case 'E': serverOpts.options |= Server::SeparateDebugAndRelease; break; case 'g': serverOpts.options |= Server::EnableNDEBUG; break; case 'Q': serverOpts.options |= Server::StartSuspended; break; case 'Z': serverOpts.rpVisitFileTimeout = atoi(optarg); if (serverOpts.rpVisitFileTimeout < 0) { fprintf(stderr, "Invalid argument to -Z %s\n", optarg); return 1; } if (!serverOpts.rpVisitFileTimeout) serverOpts.rpVisitFileTimeout = -1; break; case 'y': serverOpts.maxFileMapScopeCacheSize = atoi(optarg); if (serverOpts.maxFileMapScopeCacheSize <= 0) { fprintf(stderr, "Invalid argument to -y %s\n", optarg); return 1; } break; case 'O': serverOpts.rpConnectTimeout = atoi(optarg); if (serverOpts.rpConnectTimeout < 0) { fprintf(stderr, "Invalid argument to -O %s\n", optarg); return 1; } break; case 3: serverOpts.rpConnectAttempts = atoi(optarg); if (serverOpts.rpConnectAttempts <= 0) { fprintf(stderr, "Invalid argument to --rp-connect-attempts %s\n", optarg); return 1; } break; case 'k': serverOpts.threadStackSize = atoi(optarg); if (serverOpts.threadStackSize < 0) { fprintf(stderr, "Invalid argument to -k %s\n", optarg); return 1; } break; case 'b': serverOpts.ignoredCompilers.insert(Path::resolved(optarg)); break; case 't': { Path test(optarg); if (!test.resolve() || !test.isFile()) { fprintf(stderr, "%s doesn't seem to be a file\n", optarg); return 1; } serverOpts.tests += test; break; } case 'z': serverOpts.testTimeout = atoi(optarg); if (serverOpts.testTimeout <= 0) { fprintf(stderr, "Invalid argument to -z %s\n", optarg); return 1; } break; case 'n': serverOpts.socketFile = optarg; break; case 'd': defaultDataDir = false; serverOpts.dataDir = String::format<128>("%s", Path::resolved(optarg).constData()); break; case 'h': usage(stdout); return 0; case 'Y': serverOpts.options |= Server::NoNoUnknownWarningsOption; break; case 'p': serverOpts.options |= Server::Progress; break; case 'R': serverOpts.options |= Server::EnableCompilerManager; break; case 'm': serverOpts.options |= Server::DisallowMultipleSources; break; case 'o': serverOpts.options |= Server::NoStartupCurrentProject; break; case 'w': serverOpts.options |= Server::WatchSystemPaths; break; case 'q': serverOpts.options |= Server::SuspendRPOnCrash; break; case 'M': #ifdef OS_FreeBSD serverOpts.options &= ~Server::NoFileManagerWatch; #else serverOpts.options |= Server::NoFileManagerWatch; #endif break; case 'B': serverOpts.options |= Server::NoFileSystemWatch; break; case 'V': serverOpts.argTransform = Process::findCommand(optarg); if (strlen(optarg) && serverOpts.argTransform.isEmpty()) { fprintf(stderr, "Invalid argument to -V. Can't resolve %s", optarg); return 1; } break; case 'F': serverOpts.options |= Server::IgnorePrintfFixits; break; case 'f': serverOpts.options |= Server::NoUnlimitedErrors; break; case 'l': serverOpts.options &= ~Server::SpellChecking; break; case 'W': serverOpts.options &= ~Server::Wall; break; case 'u': serverOpts.options |= Server::Weverything; break; case 'P': serverOpts.options |= Server::AllowPedantic; break; case 'C': serverOpts.options |= Server::ClearProjects; break; case 'e': putenv(optarg); break; case 'x': sigHandler = false; break; case 'K': serverOpts.maxCrashCount = atoi(optarg); if (serverOpts.maxCrashCount <= 0) { fprintf(stderr, "Invalid argument to -K %s\n", optarg); return 1; } break; case 'i': serverOpts.completionCacheSize = atoi(optarg); if (serverOpts.completionCacheSize <= 0) { fprintf(stderr, "Invalid argument to -i %s\n", optarg); return 1; } break; case 'T': serverOpts.rpIndexDataMessageTimeout = atoi(optarg); if (serverOpts.rpIndexDataMessageTimeout <= 0) { fprintf(stderr, "Can't parse argument to -T %s.\n", optarg); return 1; } break; case 'a': { bool ok; serverOpts.rpNiceValue = String(optarg).toLong(&ok); if (!ok) { fprintf(stderr, "Can't parse argument to -a %s.\n", optarg); return 1; } break; } case 'j': serverOpts.jobCount = atoi(optarg); if (serverOpts.jobCount < 0) { fprintf(stderr, "Can't parse argument to -j %s. -j must be a positive integer.\n", optarg); return 1; } break; case 'H': serverOpts.headerErrorJobCount = atoi(optarg); if (serverOpts.headerErrorJobCount < 0) { fprintf(stderr, "Can't parse argument to -H %s. -J must be a positive integer.\n", optarg); return 1; } break; case 'r': { int large = atoi(optarg); if (large <= 0) { fprintf(stderr, "Can't parse argument to -r %s\n", optarg); return 1; } serverOpts.defaultArguments.append("-Wlarge-by-value-copy=" + String(optarg)); // ### not quite working break; } case 'D': { const char *eq = strchr(optarg, '='); Source::Define def; if (!eq) { def.define = optarg; } else { def.define = String(optarg, eq - optarg); def.value = eq + 1; } serverOpts.defines.append(def); break; } case 'I': serverOpts.includePaths.append(Source::Include(Source::Include::Type_Include, Path::resolved(optarg))); break; case 's': serverOpts.includePaths.append(Source::Include(Source::Include::Type_System, Path::resolved(optarg))); break; case 'L': logFile = optarg; logLevel = LogLevel::None; break; case 'v': if (logLevel != LogLevel::None) ++logLevel; break; #ifdef OS_Darwin case 4: serverOpts.options |= Server::Launchd; break; #endif case 5: inactivityTimeout = atoi(optarg); // seconds. if (inactivityTimeout <= 0) { fprintf(stderr, "Invalid argument to --inactivity-timeout %s\n", optarg); return 1; } break; case 7: serverOpts.options |= Server::RPLogToSyslog; break; case 8: serverOpts.options |= Server::CompletionsNoFilter; break; case '?': { fprintf(stderr, "Run rdm --help for help\n"); return 1; } } } if (optind < argCount) { fprintf(stderr, "rdm: unexpected option -- '%s'\n", args[optind]); return 1; } if (daemon) { switch (fork()) { case -1: fprintf(stderr, "Failed to fork (%d) %s\n", errno, strerror(errno)); return 1; case 0: setsid(); switch (fork()) { case -1: fprintf(stderr, "Failed to fork (%d) %s\n", errno, strerror(errno)); return 1; case 0: break; default: return 0; } break; default: return 0; } } if (serverOpts.headerErrorJobCount == -1) { serverOpts.headerErrorJobCount = std::max(1, serverOpts.jobCount / 2); } else { serverOpts.headerErrorJobCount = std::min(serverOpts.headerErrorJobCount, serverOpts.jobCount); } if (sigHandler) { signal(SIGSEGV, sigSegvHandler); signal(SIGILL, sigSegvHandler); signal(SIGABRT, sigSegvHandler); } // Shell-expand logFile Path logPath(logFile); logPath.resolve(); if (!initLogging(argv[0], LogStderr, logLevel, logPath.constData(), logFlags, logFileLogLevel)) { fprintf(stderr, "Can't initialize logging with %d %s %s\n", logLevel.toInt(), logFile ? logFile : "", logFlags.toString().constData()); return 1; } #ifdef OS_Darwin if (serverOpts.options & Server::Launchd) { // Clamp inactivity timeout. launchd starts to worry if the // process runs for less than 10 seconds. static const int MIN_INACTIVITY_TIMEOUT = 15; // includes // fudge factor. if (inactivityTimeout < MIN_INACTIVITY_TIMEOUT) { inactivityTimeout = MIN_INACTIVITY_TIMEOUT; fprintf(stderr, "launchd mode - clamped inactivity timeout to %d to avoid launchd warnings.\n", inactivityTimeout); } } #endif EventLoop::SharedPtr loop(new EventLoop); loop->init(EventLoop::MainEventLoop|EventLoop::EnableSigIntHandler|EventLoop::EnableSigTermHandler); std::shared_ptr<Server> server(new Server); if (!serverOpts.tests.isEmpty()) { char buf[1024]; Path path; while (true) { strcpy(buf, "/tmp/rtags-test-XXXXXX"); if (!mkdtemp(buf)) { fprintf(stderr, "Failed to mkdtemp (%d)\n", errno); return 1; } path = buf; path.resolve(); break; } serverOpts.dataDir = path; strcpy(buf, "/tmp/rtags-sock-XXXXXX"); const int fd = mkstemp(buf); if (fd == -1) { fprintf(stderr, "Failed to mkstemp (%d)\n", errno); return 1; } close(fd); serverOpts.socketFile = buf; serverOpts.socketFile.resolve(); } if (defaultDataDir) { Path migration = String::format<128>("%s.rtags-file", Path::home().constData()); if (migration.isDir()) { Rct::removeDirectory(serverOpts.dataDir); rename(migration.constData(), serverOpts.dataDir.constData()); error() << "Migrated datadir from ~/.rtags-file ~/.rtags"; } } serverOpts.dataDir = serverOpts.dataDir.ensureTrailingSlash(); if (!server->init(serverOpts)) { cleanupLogging(); return 1; } if (!serverOpts.tests.isEmpty()) { return server->runTests() ? 0 : 1; } loop->setInactivityTimeout(inactivityTimeout * 1000); loop->exec(); const int ret = server->exitCode(); server.reset(); cleanupLogging(); return ret; }
TogglApi::TogglApi( QObject *parent, QString logPathOverride, QString dbPathOverride) : QObject(parent) , shutdown(false) , ctx(0) { QString version = QApplication::applicationVersion(); ctx = toggl_context_init("linux_native_app", version.toStdString().c_str()); QString appDirPath = QStandardPaths::writableLocation( QStandardPaths::DataLocation); QDir appDir = QDir(appDirPath); if (!appDir.exists()) { appDir.mkpath("."); } QString logPath(""); if (logPathOverride.isEmpty()) { logPath = appDir.filePath("toggldesktop.log"); } else { logPath = logPathOverride; } toggl_set_log_path(logPath.toUtf8().constData()); qDebug() << "Log path " << logPath; toggl_set_log_level("debug"); QString dbPath(""); if (dbPathOverride.isEmpty()) { dbPath = appDir.filePath("toggldesktop.db"); } else { dbPath = dbPathOverride; } toggl_set_db_path(ctx, dbPath.toUtf8().constData()); qDebug() << "DB path " << dbPath; QString executablePath = QCoreApplication::applicationDirPath(); QDir executableDir = QDir(executablePath); QString cacertPath = executableDir.filePath("cacert.pem"); toggl_set_cacert_path(ctx, cacertPath.toUtf8().constData()); toggl_on_show_app(ctx, on_display_app); toggl_on_update(ctx, on_display_update); toggl_on_error(ctx, on_display_error); toggl_on_online_state(ctx, on_display_online_state); toggl_on_url(ctx, on_display_url); toggl_on_login(ctx, on_display_login); toggl_on_reminder(ctx, on_display_reminder); toggl_on_time_entry_list(ctx, on_display_time_entry_list); toggl_on_time_entry_autocomplete(ctx, on_display_time_entry_autocomplete); toggl_on_mini_timer_autocomplete(ctx, on_display_mini_timer_autocomplete); toggl_on_project_autocomplete(ctx, on_display_project_autocomplete); toggl_on_workspace_select(ctx, on_display_workspace_select); toggl_on_client_select(ctx, on_display_client_select); toggl_on_tags(ctx, on_display_tags); toggl_on_time_entry_editor(ctx, on_display_time_entry_editor); toggl_on_settings(ctx, on_display_settings); toggl_on_timer_state(ctx, on_display_timer_state); toggl_on_idle_notification(ctx, on_display_idle_notification); char *env = toggl_environment(ctx); if (env) { Bugsnag::releaseStage = QString(env); free(env); } instance = this; }
int main( int argc, char **argv ) { std::cout << "Skype History Exporter v1.3.0 Stable\n" << " WEBSITE: [ https://github.com/Temptin/SkypeExport ]\n"; // helps people find updated versions // prepare command line parameters po::options_description desc( "Available options" ); desc.add_options() ( "help,h", "show this help message" ) ( "db,i", po::value<std::string>()->default_value("./main.db"), "path to your Skype profile's main.db" ) ( "outpath,o", po::value<std::string>()->default_value("./ExportedHistory"), "path where all html files will be written; will be created if missing" ) ( "contacts,c", po::value<std::string>(), "space-separated list of the SkypeIDs to output; defaults to blank which outputs all contacts" ) ( "timefmt,t", po::value<std::string>()->default_value("12h"), "format of timestamps in history output; set to \"12h\" for 12-hour clock (default), \"24h\" for a 24-hour clock, \"utc12h\" for UTC-based 12-hour clock, or \"utc24h\" for UTC-based 24-hour clock" ) ; // parse and verify command line parameters po::variables_map vm; try { po::store( po::parse_command_line( argc, argv, desc ), vm ); po::notify( vm ); } catch(...) { // malformatted input of some kind, so just show the user the help and exit the program std::cout << "\nError: Invalid parameters!\n\n" << desc << "\n"; return 1; } // show the help and exit if that's what they asked for if( vm.count( "help" ) ) { std::cout << "\n" << desc << "\n"; return 0; } // detect their desired time format (24 hour or 12 hour time; default to 12h) and time reference (UTC or local time; default to local) uint8_t timeFormat = ( vm["timefmt"].as<std::string>() == "24h" || vm["timefmt"].as<std::string>() == "utc24h" ? 2 : 1 ); // used for formatTime() input, where 2=24h, 1=12h int8_t timeReference = ( vm["timefmt"].as<std::string>() == "utc12h" || vm["timefmt"].as<std::string>() == "utc24h" ? 0 : 1 ); // 0=utc, 1=local // verify the provided database and output paths and turn them into boost filesystem objects, then create the output path if needed fs::path dbPath( vm["db"].as<std::string>() ); fs::path outPath( vm["outpath"].as<std::string>() ); dbPath.make_preferred(); // formats all slashes according to operating system outPath.make_preferred(); try { if( !fs::exists( dbPath ) || !fs::is_regular_file( dbPath ) ) { std::cout << "\nError: Database " << dbPath.leaf() << " does not exist at the provided path!\n\n" << desc << "\n"; return 1; } if( fs::file_size( dbPath ) == 0 ) { std::cout << "\nError: Database " << dbPath.leaf() << " is empty!\n\n" << desc << "\n"; return 1; } if( fs::exists( outPath ) && !fs::is_directory( outPath ) ) { std::cout << "\nError: Output path " << outPath << " already exists and is not a directory!\n\n" << desc << "\n"; return 1; } else if( !fs::exists( outPath ) ) { // outPath either exists and is a directory, or doesn't exist. // we must now create the path if missing. will throw an exception on errors such as lack of write permissions. fs::create_directories( outPath ); // creates any missing directories in the given path. } } catch( const fs::filesystem_error &ex ) { std::cout << "\nError: " << ex.what() << "\n"; return 1; } // if they've provided a space-separated list of contacts to output, we need to tokenize it and store the SkypeIDs std::map<std::string,bool> outputContacts; // filled with all contacts to output, or blank to output all std::map<std::string,bool>::iterator outputContacts_it; if( vm.count( "contacts" ) ) { boost::char_separator<char> sep( " " ); boost::tokenizer< boost::char_separator<char> > tokens( vm["contacts"].as<std::string>(), sep ); for( boost::tokenizer< boost::char_separator<char> >::iterator identities_it( tokens.begin() ); identities_it != tokens.end(); ++identities_it ) { outputContacts_it = outputContacts.find( (*identities_it) ); if( outputContacts_it == outputContacts.end() ) { // makes sure we only add each unique skypeID once, even if the idiot user has provided it multiple times outputContacts.insert( std::pair<std::string,bool>( (*identities_it), false ) ); // NOTE: we initialize the skypeID as false, and will set it to true if it's been output } } } // alright, let's begin output... try { // open Skype history database SkypeParser::CSkypeParser sp( dbPath.string() ); // display all options (input database, output path, and all names to output (if specified)) std::cout << " DATABASE: [ " << dbPath << " ]\n" // note: no newline prefix (aligns it perfectly with version header) << " TIMEFMT: [ \"" << ( timeFormat == 1 ? "12h" : "24h" ) << " " << ( timeReference == 0 ? "UTC" : "Local Time" ) << "\" ]\n" << " OUTPUT: [ " << outPath << " ]\n"; if( outputContacts.size() > 0 ) { std::cout << " CONTACTS: [ \""; for( std::map<std::string,bool>::const_iterator it( outputContacts.begin() ); it != outputContacts.end(); ++it ) { std::cout << (*it).first; if( boost::next( it ) != outputContacts.end() ) { std::cout << "\", \""; // appended after every element except the last one } } std::cout << "\" ]\n\n"; } else { std::cout << " CONTACTS: [ \"*\" ]\n\n"; } // grab a list of all contacts encountered in the database const SkypeParser::skypeIDs_t &users = sp.getSkypeUsers(); // output statistics std::cout << "Found " << users.size() << " contacts in the database...\n\n"; // output contacts, skipping some in case the user provided a list of contacts to export for( SkypeParser::skypeIDs_t::const_iterator it( users.begin() ); it != users.end(); ++it ) { const std::string &skypeID = (*it); // skip if we're told to filter contacts outputContacts_it = outputContacts.find( (*it) ); // store iterator here since we'll set it to true after outputting, if contact filters are enabled if( outputContacts.size() > 0 && ( outputContacts_it == outputContacts.end() ) ) { continue; // if no filters, it's always false; if filters it's true if the contact is to be skipped } // construct the final path to the log file for this user fs::path logPath( outPath ); logPath /= ( (*it) + ".skypelog.htm" ); // appends the log filename and chooses the appropriate path separator // output exporting header std::cout << " * Exporting: " << skypeID << " (" << sp.getDisplayNameAtTime( skypeID, -1 ) << ")\n"; std::cout << " => " << logPath << "\n"; sp.exportUserHistory( skypeID, logPath.string(), timeFormat, timeReference ); if( outputContacts.size() > 0 ) { (*outputContacts_it).second = true; // since filters are enabled and we've come here, we know we've output the person as requested, so mark them as such } } } catch( const std::exception &e ) { std::cout << "Error while processing Skype database: \"" << e.what() << "\".\n"; return 1; } // check for any missing IDs if filtered output was requested for( std::map<std::string,bool>::const_iterator it( outputContacts.begin() ); it != outputContacts.end(); ++it ) { if( (*it).second == false ) { // a requested ID that was not found in the database std::cout << " * Not Found: " << (*it).first << "\n"; } } std::cout << "\nExport finished.\n"; return 0; }