#include "files_git_changes.h" #include "core.h" #include "windows_command_line.h" #include #include #include #include #include #include #include namespace ks::files { namespace { namespace fs=std::filesystem; struct GitHandle { HANDLE value{}; void close() { if(value && value!=INVALID_HANDLE_VALUE) CloseHandle(value); value=nullptr; } ~GitHandle(){close();} }; [[noreturn]] void gitWindowsError(const char *operation) { throw std::system_error(GetLastError(),std::system_category(),operation); } void makeGitPipe(GitHandle &read,GitHandle &write,SECURITY_ATTRIBUTES &inheritable) { if(!CreatePipe(&read.value,&write.value,&inheritable,0) || !SetHandleInformation(read.value,HANDLE_FLAG_INHERIT,0)) gitWindowsError("Could not create the Git output pipe"); } fs::path locateGit() { const DWORD size=GetEnvironmentVariableW(L"PATH",nullptr,0); std::wstring paths(size,L'\0'); if(size) { const auto count=GetEnvironmentVariableW(L"PATH",paths.data(),size); paths.resize(count=2 && directory.front()==L'"' && directory.back()==L'"') directory=directory.substr(1,directory.size()-2); const auto path=fs::path(directory); if(path.is_absolute()) { const auto candidate=path/L"git.exe"; const auto attributes=GetFileAttributesW(candidate.c_str()); if(attributes!=INVALID_FILE_ATTRIBUTES && !(attributes&FILE_ATTRIBUTE_DIRECTORY)) return candidate; } if(end==remaining.npos) break; remaining.remove_prefix(end+1); } for(const auto key:{HKEY_CURRENT_USER,HKEY_LOCAL_MACHINE}) { wchar_t install[32768]{}; DWORD bytes=sizeof(install); if(RegGetValueW(key,L"SOFTWARE\\GitForWindows",L"InstallPath",RRF_RT_REG_SZ,nullptr,install,&bytes)!=ERROR_SUCCESS) continue; const auto git=fs::path(install)/L"cmd"/L"git.exe"; if(git.is_absolute() && GetFileAttributesW(git.c_str())!=INVALID_FILE_ATTRIBUTES) return git; } throw std::runtime_error("Git for Windows was not found. Install it or add git.exe to PATH."); } std::vector gitEnvironment() { const auto environment=GetEnvironmentStringsW(); if(!environment) gitWindowsError("Could not read the environment for Git"); const std::unique_ptr owned(environment,FreeEnvironmentStringsW); constexpr std::wstring_view overrides[]{ L"GIT_DIR",L"GIT_WORK_TREE",L"GIT_COMMON_DIR",L"GIT_INDEX_FILE",L"GIT_PREFIX", L"GIT_CEILING_DIRECTORIES",L"GIT_GLOB_PATHSPECS",L"GIT_NOGLOB_PATHSPECS",L"GIT_ICASE_PATHSPECS"}; std::vector result; for(auto entry=environment;*entry;) { const std::wstring_view setting=entry; const auto name=setting.substr(0,setting.find(L'=')); if(std::none_of(std::begin(overrides),std::end(overrides),[&](std::wstring_view key) { return name.size()==key.size() && CompareStringOrdinal(name.data(),static_cast(name.size()),key.data(),static_cast(key.size()),TRUE) ==CSTR_EQUAL; })) result.insert(result.end(),entry,entry+setting.size()+1); entry+=setting.size()+1; } result.push_back(L'\0'); if(result.size()==1) result.push_back(L'\0'); return result; } struct GitProcessAttributes { std::vector storage; LPPROC_THREAD_ATTRIBUTE_LIST list{}; explicit GitProcessAttributes(HANDLE (&inherited)[3]) { SIZE_T bytes{}; InitializeProcThreadAttributeList(nullptr,1,0,&bytes); storage.resize(bytes); const auto attributes=reinterpret_cast(storage.data()); if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes)) gitWindowsError("Could not initialize the Git process"); if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr)) { const auto error=GetLastError(); DeleteProcThreadAttributeList(attributes); throw std::system_error(error,std::system_category(),"Could not set Git process handles"); } list=attributes; } ~GitProcessAttributes(){DeleteProcThreadAttributeList(list);} }; struct GitOutput { std::string output, error; DWORD exitCode{}; }; GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector &arguments, size_t maximum,std::stop_token stop) { if(stop.stop_requested()) throw std::runtime_error("Git request canceled."); auto command=quoteWindowsArgument(git.native())+ L" --no-pager --no-optional-locks --literal-pathspecs -c core.fsmonitor=false -c core.quotePath=false -C "+ quoteWindowsArgument(directory.native()); for(const auto &argument:arguments) command+=L' '+quoteWindowsArgument(argument); auto environment=gitEnvironment(); SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE}; const GitHandle input{CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,OPEN_EXISTING,0,nullptr)}; if(input.value==INVALID_HANDLE_VALUE) gitWindowsError("Could not open Git input"); GitHandle out,childOut,error,childError; makeGitPipe(out,childOut,inheritable); makeGitPipe(error,childError,inheritable); HANDLE inherited[]{input.value,childOut.value,childError.value}; GitProcessAttributes attributes(inherited); STARTUPINFOEXW startup{}; startup.StartupInfo.cb=sizeof(startup); startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES; startup.StartupInfo.hStdInput=input.value; startup.StartupInfo.hStdOutput=childOut.value; startup.StartupInfo.hStdError=childError.value; startup.lpAttributeList=attributes.list; PROCESS_INFORMATION child{}; if(!CreateProcessW(git.c_str(),command.data(),nullptr,nullptr,TRUE, CREATE_NO_WINDOW|CREATE_SUSPENDED|CREATE_UNICODE_ENVIRONMENT|EXTENDED_STARTUPINFO_PRESENT, environment.data(),directory.c_str(),&startup.StartupInfo,&child)) gitWindowsError("Could not start Git"); const GitHandle process{child.hProcess},thread{child.hThread}; const GitHandle job{CreateJobObjectW(nullptr,nullptr)}; JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{}; limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if(job.value && SetInformationJobObject(job.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits))) AssignProcessToJobObject(job.value,process.value); try { if(ResumeThread(thread.value)==DWORD(-1)) gitWindowsError("Could not resume Git"); childOut.close(); childError.close(); GitOutput result; const auto deadline=GetTickCount64()+15000; const auto read=[&](HANDLE pipe,std::string &data,size_t limit) { DWORD waiting{},readBytes{}; char buffer[8192]; if(!PeekNamedPipe(pipe,nullptr,0,nullptr,&waiting,nullptr)) { if(GetLastError()==ERROR_BROKEN_PIPE) return false; gitWindowsError("Could not read Git output"); } if(!waiting) return false; if(!ReadFile(pipe,buffer,std::min(waiting,sizeof(buffer)),&readBytes,nullptr)) gitWindowsError("Could not read Git output"); if(data.size()+readBytes>limit) throw std::runtime_error("Git output was too large to display."); data.append(buffer,readBytes); return readBytes!=0; }; for(;;) { if(stop.stop_requested()) throw std::runtime_error("Git request canceled."); if(GetTickCount64()>=deadline) throw std::runtime_error("Git did not respond in time."); const bool readOutput=read(out.value,result.output,maximum); const bool readErrors=read(error.value,result.error,256*1024); const auto state=WaitForSingleObject(process.value,readOutput || readErrors?0:20); if(state==WAIT_FAILED) gitWindowsError("Could not wait for Git"); if(state==WAIT_OBJECT_0 && !readOutput && !readErrors) { if(read(out.value,result.output,maximum) || read(error.value,result.error,256*1024)) continue; if(!GetExitCodeProcess(process.value,&result.exitCode)) gitWindowsError("Could not read Git status"); return result; } } } catch(...) { TerminateProcess(process.value,ERROR_CANCELLED); throw; } } void checkGit(const GitOutput &result,const char *operation,bool allowDifference=false) { if(!result.exitCode || (allowDifference && result.exitCode==1)) return; auto detail=result.error; while(!detail.empty() && (detail.back()=='\r' || detail.back()=='\n')) detail.pop_back(); throw std::runtime_error(detail.empty()?std::string(operation):std::string(operation)+"\r\n"+detail); } std::string_view nulField(std::string_view &input) { const auto separator=input.find('\0'); if(separator==input.npos) throw std::runtime_error("Git returned incomplete output."); const auto field=input.substr(0,separator); input.remove_prefix(separator+1); return field; } std::wstring statusPath(std::string_view value) { if(value.empty() || value.starts_with('/') || value.find_first_of("\\:")!=value.npos) throw std::runtime_error("Git returned an unsupported worktree path."); for(auto suffix=value;!suffix.empty();) { const auto slash=suffix.find('/'); const auto part=suffix.substr(0,slash); if(part=="." || part==".." || part.empty()) throw std::runtime_error("Git returned an unsupported worktree path."); if(slash==suffix.npos) break; suffix.remove_prefix(slash+1); } return wide(std::string(value)); } std::vector parseGitStatus(std::string_view output) { std::vector result; while(!output.empty()) { const auto row=nulField(output); if(row.size()<4 || row[2]!=' ') throw std::runtime_error("Git returned an invalid status record."); const auto code=row.substr(0,2); const auto path=statusPath(row.substr(3)); std::wstring origin; if(code.find_first_of("RC")!=code.npos) origin=statusPath(nulField(output)); if(code=="??") result.push_back({GitChangeKind::untracked,path,{},L"?"}); else if(code=="DD" || code=="AA" || code.find('U')!=code.npos) result.push_back({GitChangeKind::unstaged,path,{},wide(std::string(code))}); else { if(code[0]!=' ') result.push_back({GitChangeKind::staged,path,origin,std::wstring(1,code[0])}); if(code[1]!=' ') result.push_back({GitChangeKind::unstaged,path,origin,std::wstring(1,code[1])}); } } std::sort(result.begin(),result.end(),[](const auto &left,const auto &right) { return std::tie(left.kind,left.path) args{L"diff",L"--no-color",L"--no-ext-diff",L"--no-textconv",L"--find-renames"}; const bool untracked=change.kind==GitChangeKind::untracked; if(untracked) args.push_back(L"--no-index"); if(change.kind==GitChangeKind::staged) args.push_back(L"--cached"); args.push_back(L"--"); if(untracked) args.push_back(L"/dev/null"); else if(!change.oldPath.empty()) args.push_back(change.oldPath); args.push_back(change.path); auto patch=runGit(git,root,args,2*1024*1024,stop); checkGit(patch,"Could not read this Git diff.",untracked); return std::move(patch.output); } std::vector readGitBranches(const std::filesystem::path &git,const std::filesystem::path &root, std::stop_token stop) { const auto refs=runGit(git,root,{L"for-each-ref",L"--sort=refname", L"--format=%(objectname)%00%(refname)%00%(HEAD)%00%(symref)",L"refs/heads",L"refs/remotes"}, 4*1024*1024,stop); checkGit(refs,"Could not read Git branches."); constexpr std::string_view localPrefix="refs/heads/",remotePrefix="refs/remotes/"; std::vector branches; bool foundHead=false; for(std::string_view remaining=refs.output;!remaining.empty();) { const auto newline=remaining.find('\n'); auto line=remaining.substr(0,newline); remaining.remove_prefix(newline==remaining.npos?remaining.size():newline+1); if(line.ends_with('\r')) line.remove_suffix(1); if(line.empty()) continue; const auto revision=gitRevision(nulField(line)); const auto ref=nulField(line); const bool current=nulField(line)=="*"; if(!line.empty()) continue; // Skip aliases such as origin/HEAD. const bool remote=ref.starts_with(remotePrefix); if(!remote && !ref.starts_with(localPrefix)) continue; const auto branch=wide(std::string(ref.substr(remote?remotePrefix.size():localPrefix.size()))); branches.push_back({wide(std::string(ref)),(current?L"* ":remote?L"Tracking · ":L"Local · ")+branch, revision,current}); foundHead|=current; } if(!foundHead) { auto head=runGit(git,root,{L"rev-parse",L"--verify",L"--quiet",L"HEAD"},64*1024,stop); checkGit(head,"Could not read Git HEAD.",true); if(!head.exitCode) { while(!head.output.empty() && (head.output.back()=='\n' || head.output.back()=='\r')) head.output.pop_back(); branches.insert(branches.begin(),{L"HEAD",L"* Detached HEAD",gitRevision(head.output),true}); } } return branches; } GitHistoryPage readGitHistory(const std::filesystem::path &git,const std::filesystem::path &root, const std::wstring &revision,size_t offset,std::stop_token stop) { constexpr size_t pageSize=50; const auto log=runGit(git,root,{L"log",L"--no-decorate",L"--no-notes",L"--no-show-signature", L"--encoding=UTF-8",L"--date=short",L"--format=%H%x00%h%x00%ad%x00%s",L"-z", L"--max-count="+std::to_wstring(pageSize+1),L"--skip="+std::to_wstring(offset),revision,L"--"}, 2*1024*1024,stop); checkGit(log,"Could not read Git history."); GitHistoryPage page; std::string_view records=log.output; while(!records.empty() && page.commits.size()'); text.append("\nDate ").append(date).append("\n\n").append(message); while(!text.empty() && (text.back()=='\r' || text.back()=='\n')) text.pop_back(); const auto changes=runGit(git,root,{L"show",L"--no-notes",L"--no-show-signature",L"--format=",L"--name-status", L"-z",L"--root",L"--diff-merges=first-parent",L"--find-renames",L"--no-ext-diff",L"--no-textconv", revision,L"--"},2*1024*1024,stop); checkGit(changes,"Could not read changed paths."); text+="\n\nChanged paths\n"; if(changes.output.empty()) text+="No changed paths.\n"; std::string_view records=changes.output; while(!records.empty()) { const auto code=nulField(records); if(code.empty()) throw std::runtime_error("Git returned an invalid changed-path record."); text.append(code).append(" ").append(nulField(records)); if(code.front()=='R' || code.front()=='C') text.append(" → ").append(nulField(records)); text.push_back('\n'); } return text; } }