2017-04-23 65 views
1

我正在嘗試使用NSTask創建Git提交併向該提交添加消息。「啓動路徑不可訪問」使用NSTask創建Git提交

這是我試過的代碼。

NSString *projectPath = @"file:///Users/MYNAME/Desktop/MYPROJECT/"; 
//stage files 
NSPipe *pipe = [NSPipe pipe]; 
NSTask *task = [[NSTask alloc] init]; 
task.launchPath = projectPath; 
task.arguments = @[@"git", @"add", @"."]; 
task.standardOutput = pipe; 
[task launch]; 

//commit 
NSPipe *pipe2 = [NSPipe pipe]; 
NSTask *task2 = [[NSTask alloc] init]; 
task2.launchPath = projectPath; 
task2.arguments = @[@"git", @"commit", @"-m",@"\"Some Message\""]; 
task2.standardOutput = pipe2; 
[task2 launch]; 

我通過使用NSOpenPanel(標準OS X打開的對話框)接收projectPath

在Xcode的終端,我得到的消息 「啓動路徑無法訪問」

那我做錯了嗎?

更新 喬什 - 卡斯威爾評論之後,這是我的代碼

NSString *projectPath = @"file:///Users/MYNAME/Desktop/MYPROJECT/"; 
NSString *gitPath = @"/usr/local/bin/git"; //location of the GIT on my mac 

//stage 
NSPipe *pipe = [NSPipe pipe]; 
NSTask *task = [[NSTask alloc] init]; 
task.launchPath = gitPath; 
task.currentDirectoryPath = projectPath; 
task.arguments = @[@"add", @"."]; 
task.standardOutput = pipe; 
[task launch]; 

[任務啓動之後;我在終端「工作目錄不存在」中收到錯誤消息。

回答

1

任務的launchPath是通向要運行的程序:這是Git的在這裏,所以這條道路可能需要被/usr/local/bin/git。並從參數中刪除@"git";這不是一個參數,它是可執行文件。

您的項目路徑應該用於任務currentDirectoryPath,以便它具有正確的工作目錄。

+0

感謝您的澄清。你說的是有道理的。不幸的是,我仍然沒有這樣的運氣。當我在終端中輸入:「which git」時,我得到「/ usr/bin/git」,所以我想我應該用launchIn而不是「/ usr/local/bin/git」。但我仍然得到「發射路徑不可訪問」的錯誤。此外,當我添加「currentDirectoryPath」我得到消息「啓動路徑不可訪問」。有什麼方法可以查看正在寫入提示和哪個文件夾?爲了調試這個? – SimpleApp

+0

我不認爲有任何輸出,因爲'NSTask'本身並沒有開始。這聽起來像是存在權限或$ PATH問題,但我無法想象/ usr/bin不在$ PATH中。 –

+0

在Termainal中,我可以從任何文件夾調用git。當我輸入「echo $ PATH」時,我得到「/ usr/local/bin:/ usr/bin:/ bin:/ usr/sbin:/ sbin」 – SimpleApp

1

從Josh Casswell的回答中,我設法弄明白了。我發現我必須從projectPath中刪除「file://」部分。所以項目路徑應該是@「/ Users/MYNAME/Desktop/MYPROJECT /」。另外它不應該包含空格,因爲它不適用於%20轉義字符。這很奇怪,因爲當你使用NSOpenPanel的時候你會得到NSURL,當你調用它的絕對路徑時,你會在開始時獲得「file://」,而在路徑中獲得「%20」而不是空格。

TLDR; 此代碼在Xcode 8:

NSString *projectPath = @"/Users/MYNAME/Desktop/MYPROJECT/"; //be careful that it does not contain %20 
NSString *gitPath = @"/usr/local/bin/git"; 
NSString *message = @"this is commit message"; 

//stage 
NSPipe *pipe = [NSPipe pipe]; 
NSTask *task = [[NSTask alloc] init]; 
task.launchPath = gitPath; 
task.currentDirectoryPath = projectPath; 
task.arguments = @[@"add", @"."]; 
task.standardOutput = pipe; 
[task launch]; 
[task waitUntilExit]; 

//commit 
NSPipe *pipe2 = [NSPipe pipe]; 
NSTask *task2 = [[NSTask alloc] init]; 
task2.launchPath = gitPath; 
task2.currentDirectoryPath = projectPath; 
task2.arguments = @[@"commit", @"-m", message]; 
task2.standardOutput = pipe2; 
[task2 launch]; 
[task2 waitUntilExit]; 

更新 添加[任務waitUntilExit] 如果你不斷收到消息

致命的:無法創建 「/Users/MYNAME/Desktop/MYPROJECT/.git/index.lock」:文件存在。

另一個git過程似乎在這個倉庫中運行,例如,由'git commit'打開的編輯器 。請確保所有進程都是 終止,然後再試一次。如果仍然失敗,git進程可能會在早期崩潰在此版本庫中: 繼續。

+0

很高興你知道了;隨意將答案標上自己的答案,因爲它似乎比我的更完整。 –

+0

至於路徑,你可能想使用' - [NSURL path]'而不是'absolutePath'。你會注意到這些空格是非轉義的,並且不包括scheme('file://')。 –