Files
hrynco-kswitcher/src/files_git_changes.cpp
T

411 lines
18 KiB
C++

#include "files_git_changes.h"
#include "core.h"
#include "windows_command_line.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <system_error>
#include <tuple>
#include <utility>
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<size?count:0);
}
std::wstring_view remaining=paths;
while(!remaining.empty())
{
const auto end=remaining.find(L';');
auto directory=remaining.substr(0,end);
if(directory.size()>=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<wchar_t> gitEnvironment()
{
const auto environment=GetEnvironmentStringsW();
if(!environment) gitWindowsError("Could not read the environment for Git");
const std::unique_ptr<wchar_t,decltype(&FreeEnvironmentStringsW)> 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<wchar_t> 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<int>(name.size()),key.data(),static_cast<int>(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<std::byte> 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<LPPROC_THREAD_ATTRIBUTE_LIST>(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<std::wstring> &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<DWORD>(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<GitChange> parseGitStatus(std::string_view output)
{
std::vector<GitChange> 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)<std::tie(right.kind,right.path);
});
return result;
}
std::wstring gitRevision(std::string_view value)
{
if((value.size()!=40 && value.size()!=64) || value.find_first_not_of("0123456789abcdef")!=value.npos)
throw std::runtime_error("Git returned an invalid object ID.");
return {value.begin(),value.end()};
}
}
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.");
while(!root.output.empty() && (root.output.back()=='\r' || root.output.back()=='\n')) root.output.pop_back();
result.root=fs::path(wide(root.output)).make_preferred();
if(!result.root.is_absolute()) throw std::runtime_error("Git returned an invalid worktree root.");
const auto status=runGit(result.executable,result.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.");
result.entries=parseGitStatus(status.output);
return result;
}
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
const GitChange &change,std::stop_token stop)
{
std::vector<std::wstring> 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<GitBranch> 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<GitBranch> 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()<pageSize)
page.commits.push_back({gitRevision(nulField(records)),wide(std::string(nulField(records))),
wide(std::string(nulField(records))),wide(std::string(nulField(records)))});
page.more=!records.empty();
return page;
}
std::string readGitCommit(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,std::stop_token stop)
{
const auto metadata=runGit(git,root,{L"log",L"-1",L"--no-decorate",L"--no-notes",L"--no-show-signature",
L"--encoding=UTF-8",L"--format=%H%x00%an%x00%ae%x00%aI%x00%B",L"-z",revision,L"--"},2*1024*1024,stop);
checkGit(metadata,"Could not read the Git commit.");
std::string_view parts=metadata.output;
const auto id=nulField(parts);
const auto author=nulField(parts);
const auto email=nulField(parts);
const auto date=nulField(parts);
const auto message=nulField(parts);
std::string text="Commit ";
text.append(id).append("\nAuthor ").append(author);
if(!email.empty()) text.append(" <").append(email).push_back('>');
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;
}
}