@@ -16,6 +16,7 @@ import (
1616const (
1717 GH_CONFIG_DIR = "GH_CONFIG_DIR"
1818 XDG_CONFIG_HOME = "XDG_CONFIG_HOME"
19+ XDG_STATE_HOME = "XDG_STATE_HOME"
1920 APP_DATA = "AppData"
2021)
2122
@@ -51,30 +52,84 @@ func ConfigDir() string {
5152func autoMigrateConfigDir (newPath string ) {
5253 path , err := os .UserHomeDir ()
5354 if oldPath := filepath .Join (path , ".config" , "gh" ); err == nil && dirExists (oldPath ) {
54- migrateConfigDir (oldPath , newPath )
55+ migrateDir (oldPath , newPath )
5556 return
5657 }
5758
5859 path , err = homedir .Dir ()
5960 if oldPath := filepath .Join (path , ".config" , "gh" ); err == nil && dirExists (oldPath ) {
60- migrateConfigDir (oldPath , newPath )
61+ migrateDir (oldPath , newPath )
6162 }
6263}
6364
64- func dirExists (path string ) bool {
65- f , err := os .Stat (path )
66- return err == nil && f .IsDir ()
65+ func StateDir () string {
66+ if path := os .Getenv (XDG_STATE_HOME ); path != "" {
67+ path = filepath .Join (path , "gh" )
68+ if _ , err := os .Stat (path ); errors .Is (err , os .ErrNotExist ) {
69+ _ = os .MkdirAll (path , 0755 )
70+ autoMigrateStateDir (path )
71+ }
72+ return path
73+ }
74+
75+ return ConfigDir ()
76+ }
77+
78+ // Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)
79+ // If state file exist then move it to newPath
80+ // TODO: Remove support for homedir.Dir location in v2
81+ func autoMigrateStateDir (newPath string ) {
82+ path , err := os .UserHomeDir ()
83+ if oldPath := filepath .Join (path , ".config" , "gh" ); err == nil && dirExists (oldPath ) {
84+ migrateFile (oldPath , newPath , "state.yml" )
85+ return
86+ }
87+
88+ path , err = homedir .Dir ()
89+ if oldPath := filepath .Join (path , ".config" , "gh" ); err == nil && dirExists (oldPath ) {
90+ migrateFile (oldPath , newPath , "state.yml" )
91+ }
92+ }
93+
94+ func migrateFile (oldPath , newPath , file string ) {
95+ if oldPath == newPath {
96+ return
97+ }
98+
99+ oldFile := filepath .Join (oldPath , file )
100+ newFile := filepath .Join (newPath , file )
101+
102+ if ! fileExists (oldFile ) {
103+ return
104+ }
105+
106+ _ = os .MkdirAll (filepath .Dir (newFile ), 0755 )
107+ _ = os .Rename (oldFile , newFile )
67108}
68109
69- var migrateConfigDir = func (oldPath , newPath string ) {
110+ func migrateDir (oldPath , newPath string ) {
70111 if oldPath == newPath {
71112 return
72113 }
73114
115+ if ! dirExists (oldPath ) {
116+ return
117+ }
118+
74119 _ = os .MkdirAll (filepath .Dir (newPath ), 0755 )
75120 _ = os .Rename (oldPath , newPath )
76121}
77122
123+ func dirExists (path string ) bool {
124+ f , err := os .Stat (path )
125+ return err == nil && f .IsDir ()
126+ }
127+
128+ func fileExists (path string ) bool {
129+ f , err := os .Stat (path )
130+ return err == nil && ! f .IsDir ()
131+ }
132+
78133func ConfigFile () string {
79134 return filepath .Join (ConfigDir (), "config.yml" )
80135}
0 commit comments