#include "files_git_changes.h" #include "core.h" #include "windows_command_line.h" #include #include #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 fs::path &alternateIndex) { 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_OBJECT_DIRECTORY",L"GIT_ALTERNATE_OBJECT_DIRECTORIES",L"GIT_NAMESPACE",L"GIT_QUARANTINE_PATH", L"GIT_CEILING_DIRECTORIES",L"GIT_GLOB_PATHSPECS",L"GIT_NOGLOB_PATHSPECS",L"GIT_ICASE_PATHSPECS"}; std::vector settings; 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; })) settings.emplace_back(setting); entry+=setting.size()+1; } if(!alternateIndex.empty()) settings.push_back(L"GIT_INDEX_FILE="+alternateIndex.native()); std::sort(settings.begin(),settings.end(),[](const auto &left,const auto &right) { return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)==CSTR_LESS_THAN; }); std::vector result; for(const auto &setting:settings) result.insert(result.end(),setting.c_str(),setting.c_str()+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{}; }; struct GitCommandOptions { fs::path index; std::string_view input; std::function afterPrepare; ULONGLONG timeout=15000; }; GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector &arguments, size_t maximum,std::stop_token stop,const GitCommandOptions &options={}) { 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(options.index); SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE}; GitHandle input,writeInput; if(options.input.empty()) { input.value=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"); } else if(!CreatePipe(&input.value,&writeInput.value,&inheritable,65536) || !SetHandleInformation(writeInput.value,HANDLE_FLAG_INHERIT,0)) 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"); input.close(); childOut.close(); childError.close(); const auto write=[&](std::string_view payload) { DWORD written{}; if(payload.size()>65536 || !WriteFile(writeInput.value,payload.data(), static_cast(payload.size()),&written,nullptr) || written!=payload.size()) gitWindowsError("Could not send input to Git"); }; if(writeInput.value) write(options.input); if(!options.afterPrepare) writeInput.close(); GitOutput result; auto deadline=GetTickCount64()+options.timeout; 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); if(writeInput.value && (result.output.find("prepare: ok\n")!=std::string::npos || result.output.find("prepare: ok\r\n")!=std::string::npos)) { options.afterPrepare(); write("commit\n"); writeInput.close(); deadline=GetTickCount64()+options.timeout; } 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(...) { const bool wasWaitingForInput=writeInput.value!=nullptr; writeInput.close(); // EOF aborts a prepared Git reference transaction. if(!wasWaitingForInput || WaitForSingleObject(process.value,2000)!=WAIT_OBJECT_0) 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) readStatus(const fs::path &git,const fs::path &root,std::stop_token stop) { const auto status=runGit(git,root,{L"status",L"--porcelain=v1",L"-z",L"--untracked-files=all",L"--renames"}, 8*1024*1024,stop); checkGit(status,"Could not read Git worktree status."); return parseGitStatus(status.output); } struct GitWorktreeFiles { fs::path index; std::vector> operations; }; GitWorktreeFiles findWorktreeFiles(const GitChanges &worktree,std::stop_token stop) { constexpr std::pair markers[]{ {L"MERGE_HEAD","merge"},{L"CHERRY_PICK_HEAD","cherry-pick"},{L"REVERT_HEAD","revert"}, {L"rebase-merge","rebase"},{L"rebase-apply","rebase or am"},{L"sequencer","sequencer"}, {L"BISECT_START","bisect"}}; std::vector args{L"rev-parse",L"--path-format=absolute",L"--git-path",L"index"}; for(const auto &[name,operation]:markers) { args.push_back(L"--git-path"); args.push_back(name); } const auto paths=runGit(worktree.executable,worktree.root,args,256*1024,stop); checkGit(paths,"Could not find the worktree index."); std::string_view lines=paths.output; const auto next=[&] { if(lines.empty()) throw std::runtime_error("Git returned incomplete worktree metadata."); const auto separator=lines.find('\n'); auto line=lines.substr(0,separator); lines.remove_prefix(separator==lines.npos?lines.size():separator+1); if(line.ends_with('\r')) line.remove_suffix(1); auto path=fs::path(wide(std::string(line))).make_preferred(); if(!path.is_absolute()) throw std::runtime_error("Git returned an invalid worktree path."); return path; }; GitWorktreeFiles result{next(),{}}; for(const auto &[name,operation]:markers) result.operations.emplace_back(next(),operation); return result; } struct WorktreeIndexLock { GitHandle file; explicit WorktreeIndexLock(const fs::path &index) { auto name=index; name+=L".lock"; file.value=CreateFileW(name.c_str(),GENERIC_WRITE|DELETE,0,nullptr,CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr); if(file.value!=INVALID_HANDLE_VALUE) return; const auto error=GetLastError(); if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS || error==ERROR_SHARING_VIOLATION) throw std::runtime_error("Git index is locked. Finish the other Git operation, then refresh."); throw std::system_error(error,std::system_category(),"Could not lock the Git index"); } WorktreeIndexLock(const WorktreeIndexLock &)=delete; }; struct WorktreeIndexCopy { fs::path path; explicit WorktreeIndexCopy(const fs::path &index) { GUID id{}; wchar_t name[40]{}; if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,static_cast(std::size(name)))) throw std::runtime_error("Could not name the temporary Git index."); path=index; path+=std::wstring(L".kswitcher-")+name; if(CopyFileW(index.c_str(),path.c_str(),TRUE)) return; const auto error=GetLastError(); if(error!=ERROR_FILE_NOT_FOUND) throw std::system_error(error,std::system_category(),"Could not copy the worktree index"); } WorktreeIndexCopy(const WorktreeIndexCopy &)=delete; ~WorktreeIndexCopy() { DeleteFileW(path.c_str()); const auto lock=path.native()+L".lock"; DeleteFileW(lock.c_str()); } void publish(const fs::path &index) const { if(!MoveFileExW(path.c_str(),index.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)) gitWindowsError("Could not replace the Git index"); } }; void requireWritableWorktree(const GitChanges &worktree,const GitWorktreeFiles &paths, const GitCheckout &checkout,std::stop_token stop) { if(!checkout.ref.starts_with(L"refs/heads/")) throw std::runtime_error("This worktree has detached HEAD. Check out a branch before writing Git changes."); for(const auto &[path,operation]:paths.operations) { if(GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES) throw std::runtime_error(std::string("A Git ")+operation+" is in progress. Finish it before writing changes."); const auto error=GetLastError(); if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_PATH_NOT_FOUND) throw std::system_error(error,std::system_category(),"Could not check for active Git operations"); } const auto conflicts=runGit(worktree.executable,worktree.root,{L"ls-files",L"--unmerged",L"-z"},2*1024*1024,stop); checkGit(conflicts,"Could not check Git index conflicts."); if(!conflicts.output.empty()) throw std::runtime_error("The Git index contains conflicts. Resolve them before writing changes."); } GitCommitReview captureGitReview(const GitChanges &worktree,const GitCheckout &checkout,std::stop_token stop, bool listPaths) { GitCommitReview review{worktree.root,checkout,{},{}}; std::vector args{L"diff",L"--cached",L"--no-color",L"--no-ext-diff",L"--no-textconv", L"--ita-invisible-in-index",L"-z"}; if(!checkout.revision.empty()) args.push_back(checkout.revision); args.push_back(L"--"); auto identityArgs=args; identityArgs.insert(identityArgs.begin()+1,{L"--raw",L"--no-renames",L"--abbrev=64"}); auto identity=runGit(worktree.executable,worktree.root,identityArgs,16*1024*1024,stop); checkGit(identity,"Could not read the staged snapshot."); review.stagedIdentity=std::move(identity.output); if(!listPaths || review.stagedIdentity.empty()) return review; args.insert(args.begin()+1,{L"--name-status",L"--find-renames"}); const auto changed=runGit(worktree.executable,worktree.root,args,8*1024*1024,stop); checkGit(changed,"Could not list all staged paths."); std::string_view records=changed.output; while(!records.empty()) { const auto flags=nulField(records); if(flags.empty()) throw std::runtime_error("Git returned an invalid staged-path record."); auto path=statusPath(nulField(records)); std::wstring old; if(flags.front()=='R' || flags.front()=='C') { old=std::move(path); path=statusPath(nulField(records)); } review.staged.push_back({GitChangeKind::staged,std::move(path),std::move(old),wide(std::string(flags))}); } return review; } } GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop) { GitChanges result; result.executable=locateGit(); auto root=runGit(result.executable,directory,{L"rev-parse",L"--show-toplevel"},64*1024,stop); checkGit(root,"This folder is not inside a Git worktree."); trimGitLine(root.output); result.root=fs::path(wide(root.output)).make_preferred(); if(!result.root.is_absolute()) throw std::runtime_error("Git returned an invalid worktree root."); result.checkout=readCheckout(result.executable,result.root,stop); result.entries=readStatus(result.executable,result.root,stop); return result; } std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root, const GitChange &change,std::stop_token stop) { std::vector 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; } void changeGitIndex(const GitChanges &worktree,const GitChange &entry,bool replaceStaged,std::stop_token stop) { const auto paths=findWorktreeFiles(worktree,stop); const WorktreeIndexLock lock(paths.index); const auto checkout=readCheckout(worktree.executable,worktree.root,stop); requireWritableWorktree(worktree,paths,checkout,stop); if(checkout!=worktree.checkout) throw std::runtime_error("The checked-out branch or commit changed. Review the refreshed Git changes."); const auto entries=readStatus(worktree.executable,worktree.root,stop); if(std::find(entries.begin(),entries.end(),entry)==entries.end()) throw std::runtime_error("The selected change is no longer current. Review the refreshed Git changes."); const bool stage=entry.kind!=GitChangeKind::staged; const bool rename=entry.flags.starts_with(L"R") || entry.flags.starts_with(L"C"); const auto overlaps=[&](const GitChange &other) { return other.kind==GitChangeKind::staged && (other.path==entry.path || other.oldPath==entry.path || (rename && !entry.oldPath.empty() && (other.path==entry.oldPath || other.oldPath==entry.oldPath))); }; if(stage && !replaceStaged && std::any_of(entries.begin(),entries.end(),overlaps)) throw std::runtime_error("The selected path already has staged changes. Review and confirm the replacement."); if(stage) { const auto attributes=GetFileAttributesW((worktree.root/fs::path(entry.path)).c_str()); if(entry.path.ends_with(L'/') || (attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY))) { const auto indexed=runGit(worktree.executable,worktree.root,{L"ls-files",L"--stage",L"--",entry.path}, 256*1024,stop); checkGit(indexed,"Could not identify the selected directory."); if(!indexed.output.starts_with("160000 ")) throw std::runtime_error("This entry is a directory. Stage individual files or an existing submodule."); } } const WorktreeIndexCopy pending(paths.index); std::vector args; if(stage) args={L"add",L"-A",L"--"}; else if(checkout.revision.empty()) args={L"rm",L"--cached",L"-f",L"--ignore-unmatch",L"--"}; else args={L"restore",L"--staged",L"--source="+checkout.revision,L"--"}; if(rename && !entry.oldPath.empty()) args.push_back(entry.oldPath); args.push_back(entry.path); const auto result=runGit(worktree.executable,worktree.root,args,1024*1024,stop,{.index=pending.path}); checkGit(result,stage?"Could not stage the selected path.":"Could not unstage the selected path."); if(readCheckout(worktree.executable,worktree.root,stop)!=checkout || stop.stop_requested()) throw std::runtime_error("The checkout changed while Git was working. Review the refreshed Git changes."); requireWritableWorktree(worktree,paths,checkout,stop); if(stop.stop_requested()) throw std::runtime_error("Git request canceled."); pending.publish(paths.index); } GitCommitReview reviewGitCommit(const GitChanges &worktree,std::stop_token stop) { const auto paths=findWorktreeFiles(worktree,stop); const WorktreeIndexLock lock(paths.index); const auto checkout=readCheckout(worktree.executable,worktree.root,stop); requireWritableWorktree(worktree,paths,checkout,stop); auto review=captureGitReview(worktree,checkout,stop,true); if(readCheckout(worktree.executable,worktree.root,stop)!=checkout) throw std::runtime_error("The checkout changed while reading the staged paths. Open a new review."); if(review.staged.empty()) throw std::runtime_error("Stage at least one change before committing."); return review; } std::wstring createGitCommit(const GitChanges &worktree,const GitCommitReview &review, const std::wstring &message,std::stop_token stop) { if(message.find_first_not_of(L" \t\r\n")==message.npos) throw std::runtime_error("Enter a commit message."); if(worktree.root!=review.root || review.stagedIdentity.empty()) throw std::runtime_error("The reviewed worktree changed. Open a new review."); const auto paths=findWorktreeFiles(worktree,stop); const WorktreeIndexLock lock(paths.index); const auto checkout=readCheckout(worktree.executable,worktree.root,stop); requireWritableWorktree(worktree,paths,checkout,stop); if(checkout!=review.checkout || captureGitReview(worktree,checkout,stop,false).stagedIdentity!=review.stagedIdentity) throw std::runtime_error("The checkout or staged changes changed after review. Review them again. The message was kept."); const WorktreeIndexCopy pending(paths.index); auto tree=runGit(worktree.executable,worktree.root,{L"write-tree"},64*1024,stop,{.index=pending.path}); checkGit(tree,"Could not write the reviewed Git tree."); trimGitLine(tree.output); const auto treeId=gitRevision(tree.output); auto signing=runGit(worktree.executable,worktree.root,{L"config",L"--type=bool",L"--get",L"commit.gpgSign"},64*1024,stop); checkGit(signing,"Could not read Git signing settings.",true); trimGitLine(signing.output); std::vector args{L"commit-tree",treeId,L"-F",L"-"}; if(!checkout.revision.empty()) args.insert(args.end(),{L"-p",checkout.revision}); if(signing.output=="true") args.push_back(L"-S"); auto contents=utf8(message); for(size_t pos=0;(pos=contents.find('\r',pos))!=contents.npos;) { if(pos+1