1+ var git = require ( '../' ) ,
2+ path = require ( 'path' ) ,
3+ fs = require ( 'fs' ) ,
4+ fileName = 'newfile.txt' ,
5+ fileContent = 'hello world'
6+ ;
7+
8+ /**
9+ * This example creates a certain file `newfile.txt`, adds it to the git index and
10+ * commits it to head. Similar to a `git add newfile.txt` followed by a `git commit`
11+ **/
12+
13+ //open a git repo
14+ git . Repo . open ( path . resolve ( __dirname , '../.git' ) , function ( openReporError , repo ) {
15+ if ( openReporError ) throw openReporError ;
16+
17+ //create the file in the repo's workdir
18+ fs . writeFile ( path . join ( repo . workdir ( ) , fileName ) , fileContent , function ( writeError ) {
19+ if ( writeError ) throw writeError ;
20+
21+ //add the file to the index...
22+ repo . openIndex ( function ( openIndexError , index ) {
23+ if ( openIndexError ) throw openIndexError ;
24+
25+ index . read ( function ( readError ) {
26+ if ( readError ) throw readError ;
27+
28+ index . addByPath ( fileName , function ( addByPathError ) {
29+ if ( addByPathError ) throw addByPathError ;
30+
31+ index . write ( function ( writeError ) {
32+ if ( writeError ) throw writeError ;
33+
34+ index . writeTree ( function ( writeTreeError , oid ) {
35+ if ( writeTreeError ) throw writeTreeError ;
36+
37+ //get HEAD
38+ git . Reference . oidForName ( repo , 'HEAD' , function ( oidForName , head ) {
39+ if ( oidForName ) throw oidForName ;
40+
41+ //get latest commit (will be the parent commit)
42+ repo . getCommit ( head , function ( getCommitError , parent ) {
43+ if ( getCommitError ) throw getCommitError ;
44+ var author = git . Signature . create ( "Scott Chacon" , "schacon@gmail.com" , 123456789 , 60 ) ;
45+ var committer = git . Signature . create ( "Scott A Chacon" , "scott@github.com" , 987654321 , 90 ) ;
46+
47+ //commit
48+ repo . createCommit ( 'HEAD' , author , committer , 'message' , oid , [ parent ] , function ( error , commitId ) {
49+ console . log ( "New Commit:" , commitId . sha ( ) ) ;
50+ } ) ;
51+ } ) ;
52+ } ) ;
53+ } ) ;
54+ } ) ;
55+ } ) ;
56+ } ) ;
57+ } ) ;
58+ } ) ;
59+ } ) ;
0 commit comments