repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/states/mac_keychain.py
installed
def installed(name, password, keychain="/Library/Keychains/System.keychain", **kwargs): ''' Install a p12 certificate file into the macOS keychain name The certificate to install password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section keychain The keychain to install the certificate to, this defaults to /Library/Keychains/System.keychain allow_any Allow any application to access the imported certificate without warning keychain_password If your keychain is likely to be locked pass the password and it will be unlocked before running the import ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if 'http' in name or 'salt' in name: name = __salt__['cp.cache_file'](name) certs = __salt__['keychain.list_certs'](keychain) friendly_name = __salt__['keychain.get_friendly_name'](name, password) if friendly_name in certs: file_hash = __salt__['keychain.get_hash'](name, password) keychain_hash = __salt__['keychain.get_hash'](friendly_name) if file_hash != keychain_hash: out = __salt__['keychain.uninstall'](friendly_name, keychain, keychain_password=kwargs.get('keychain_password')) if "unable" not in out: ret['comment'] += "Found a certificate with the same name but different hash, removing it.\n" ret['changes']['uninstalled'] = friendly_name # Reset the certs found certs = __salt__['keychain.list_certs'](keychain) else: ret['result'] = False ret['comment'] += "Found an incorrect cert but was unable to uninstall it: {0}".format(friendly_name) return ret if friendly_name not in certs: out = __salt__['keychain.install'](name, password, keychain, **kwargs) if "imported" in out: ret['changes']['installed'] = friendly_name else: ret['result'] = False ret['comment'] += "Failed to install {0}".format(friendly_name) else: ret['comment'] += "{0} already installed.".format(friendly_name) return ret
python
def installed(name, password, keychain="/Library/Keychains/System.keychain", **kwargs): ''' Install a p12 certificate file into the macOS keychain name The certificate to install password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section keychain The keychain to install the certificate to, this defaults to /Library/Keychains/System.keychain allow_any Allow any application to access the imported certificate without warning keychain_password If your keychain is likely to be locked pass the password and it will be unlocked before running the import ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if 'http' in name or 'salt' in name: name = __salt__['cp.cache_file'](name) certs = __salt__['keychain.list_certs'](keychain) friendly_name = __salt__['keychain.get_friendly_name'](name, password) if friendly_name in certs: file_hash = __salt__['keychain.get_hash'](name, password) keychain_hash = __salt__['keychain.get_hash'](friendly_name) if file_hash != keychain_hash: out = __salt__['keychain.uninstall'](friendly_name, keychain, keychain_password=kwargs.get('keychain_password')) if "unable" not in out: ret['comment'] += "Found a certificate with the same name but different hash, removing it.\n" ret['changes']['uninstalled'] = friendly_name # Reset the certs found certs = __salt__['keychain.list_certs'](keychain) else: ret['result'] = False ret['comment'] += "Found an incorrect cert but was unable to uninstall it: {0}".format(friendly_name) return ret if friendly_name not in certs: out = __salt__['keychain.install'](name, password, keychain, **kwargs) if "imported" in out: ret['changes']['installed'] = friendly_name else: ret['result'] = False ret['comment'] += "Failed to install {0}".format(friendly_name) else: ret['comment'] += "{0} already installed.".format(friendly_name) return ret
[ "def", "installed", "(", "name", ",", "password", ",", "keychain", "=", "\"/Library/Keychains/System.keychain\"", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "...
Install a p12 certificate file into the macOS keychain name The certificate to install password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section keychain The keychain to install the certificate to, this defaults to /Library/Keychains/System.keychain allow_any Allow any application to access the imported certificate without warning keychain_password If your keychain is likely to be locked pass the password and it will be unlocked before running the import
[ "Install", "a", "p12", "certificate", "file", "into", "the", "macOS", "keychain" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mac_keychain.py#L36-L98
train
saltstack/salt
salt/states/mac_keychain.py
uninstalled
def uninstalled(name, password, keychain="/Library/Keychains/System.keychain", keychain_password=None): ''' Uninstall a p12 certificate file from the macOS keychain name The certificate to uninstall, this can be a path for a .p12 or the friendly name password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section cert_name The friendly name of the certificate, this can be used instead of giving a certificate keychain The keychain to remove the certificate from, this defaults to /Library/Keychains/System.keychain keychain_password If your keychain is likely to be locked pass the password and it will be unlocked before running the import ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} certs = __salt__['keychain.list_certs'](keychain) if ".p12" in name: if 'http' in name or 'salt' in name: name = __salt__['cp.cache_file'](name) friendly_name = __salt__['keychain.get_friendly_name'](name, password) else: friendly_name = name if friendly_name in certs: out = __salt__['keychain.uninstall'](friendly_name, keychain, keychain_password) if "unable" not in out: ret['changes']['uninstalled'] = friendly_name else: ret['result'] = False ret['comment'] += "Failed to uninstall {0}".format(friendly_name) else: ret['comment'] += "{0} already uninstalled.".format(friendly_name) return ret
python
def uninstalled(name, password, keychain="/Library/Keychains/System.keychain", keychain_password=None): ''' Uninstall a p12 certificate file from the macOS keychain name The certificate to uninstall, this can be a path for a .p12 or the friendly name password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section cert_name The friendly name of the certificate, this can be used instead of giving a certificate keychain The keychain to remove the certificate from, this defaults to /Library/Keychains/System.keychain keychain_password If your keychain is likely to be locked pass the password and it will be unlocked before running the import ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} certs = __salt__['keychain.list_certs'](keychain) if ".p12" in name: if 'http' in name or 'salt' in name: name = __salt__['cp.cache_file'](name) friendly_name = __salt__['keychain.get_friendly_name'](name, password) else: friendly_name = name if friendly_name in certs: out = __salt__['keychain.uninstall'](friendly_name, keychain, keychain_password) if "unable" not in out: ret['changes']['uninstalled'] = friendly_name else: ret['result'] = False ret['comment'] += "Failed to uninstall {0}".format(friendly_name) else: ret['comment'] += "{0} already uninstalled.".format(friendly_name) return ret
[ "def", "uninstalled", "(", "name", ",", "password", ",", "keychain", "=", "\"/Library/Keychains/System.keychain\"", ",", "keychain_password", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", ...
Uninstall a p12 certificate file from the macOS keychain name The certificate to uninstall, this can be a path for a .p12 or the friendly name password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section cert_name The friendly name of the certificate, this can be used instead of giving a certificate keychain The keychain to remove the certificate from, this defaults to /Library/Keychains/System.keychain keychain_password If your keychain is likely to be locked pass the password and it will be unlocked before running the import
[ "Uninstall", "a", "p12", "certificate", "file", "from", "the", "macOS", "keychain" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mac_keychain.py#L101-L151
train
saltstack/salt
salt/states/mac_keychain.py
default_keychain
def default_keychain(name, domain="user", user=None): ''' Set the default keychain to use name The chain in which to use as the default domain The domain to use valid values are user|system|common|dynamic, the default is user user The user to run as ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if not os.path.exists(name): ret['result'] = False ret['comment'] += "Keychain not found at {0}".format(name) else: out = __salt__['keychain.get_default_keychain'](user, domain) if name in out: ret['comment'] += "{0} was already the default keychain.".format(name) else: out = __salt__['keychain.set_default_keychain'](name, domain, user) if not out: ret['changes']['default'] = name else: ret['result'] = False ret['comment'] = 'Failed to install keychain. {0}'.format(out) return ret
python
def default_keychain(name, domain="user", user=None): ''' Set the default keychain to use name The chain in which to use as the default domain The domain to use valid values are user|system|common|dynamic, the default is user user The user to run as ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if not os.path.exists(name): ret['result'] = False ret['comment'] += "Keychain not found at {0}".format(name) else: out = __salt__['keychain.get_default_keychain'](user, domain) if name in out: ret['comment'] += "{0} was already the default keychain.".format(name) else: out = __salt__['keychain.set_default_keychain'](name, domain, user) if not out: ret['changes']['default'] = name else: ret['result'] = False ret['comment'] = 'Failed to install keychain. {0}'.format(out) return ret
[ "def", "default_keychain", "(", "name", ",", "domain", "=", "\"user\"", ",", "user", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "if...
Set the default keychain to use name The chain in which to use as the default domain The domain to use valid values are user|system|common|dynamic, the default is user user The user to run as
[ "Set", "the", "default", "keychain", "to", "use" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mac_keychain.py#L154-L189
train
saltstack/salt
salt/netapi/rest_cherrypy/wsgi.py
bootstrap_app
def bootstrap_app(): ''' Grab the opts dict of the master config by trying to import Salt ''' from salt.netapi.rest_cherrypy import app import salt.config __opts__ = salt.config.client_config( os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master')) return app.get_app(__opts__)
python
def bootstrap_app(): ''' Grab the opts dict of the master config by trying to import Salt ''' from salt.netapi.rest_cherrypy import app import salt.config __opts__ = salt.config.client_config( os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master')) return app.get_app(__opts__)
[ "def", "bootstrap_app", "(", ")", ":", "from", "salt", ".", "netapi", ".", "rest_cherrypy", "import", "app", "import", "salt", ".", "config", "__opts__", "=", "salt", ".", "config", ".", "client_config", "(", "os", ".", "environ", ".", "get", "(", "'SALT...
Grab the opts dict of the master config by trying to import Salt
[ "Grab", "the", "opts", "dict", "of", "the", "master", "config", "by", "trying", "to", "import", "Salt" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/wsgi.py#L55-L64
train
saltstack/salt
salt/netapi/rest_cherrypy/wsgi.py
get_application
def get_application(*args): ''' Returns a WSGI application function. If you supply the WSGI app and config it will use that, otherwise it will try to obtain them from a local Salt installation ''' opts_tuple = args def wsgi_app(environ, start_response): root, _, conf = opts_tuple or bootstrap_app() cherrypy.config.update({'environment': 'embedded'}) cherrypy.tree.mount(root, '/', conf) return cherrypy.tree(environ, start_response) return wsgi_app
python
def get_application(*args): ''' Returns a WSGI application function. If you supply the WSGI app and config it will use that, otherwise it will try to obtain them from a local Salt installation ''' opts_tuple = args def wsgi_app(environ, start_response): root, _, conf = opts_tuple or bootstrap_app() cherrypy.config.update({'environment': 'embedded'}) cherrypy.tree.mount(root, '/', conf) return cherrypy.tree(environ, start_response) return wsgi_app
[ "def", "get_application", "(", "*", "args", ")", ":", "opts_tuple", "=", "args", "def", "wsgi_app", "(", "environ", ",", "start_response", ")", ":", "root", ",", "_", ",", "conf", "=", "opts_tuple", "or", "bootstrap_app", "(", ")", "cherrypy", ".", "conf...
Returns a WSGI application function. If you supply the WSGI app and config it will use that, otherwise it will try to obtain them from a local Salt installation
[ "Returns", "a", "WSGI", "application", "function", ".", "If", "you", "supply", "the", "WSGI", "app", "and", "config", "it", "will", "use", "that", "otherwise", "it", "will", "try", "to", "obtain", "them", "from", "a", "local", "Salt", "installation" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/wsgi.py#L67-L82
train
saltstack/salt
salt/returners/sqlite3_return.py
_get_conn
def _get_conn(ret=None): ''' Return a sqlite3 database connection ''' # Possible todo: support detect_types, isolation_level, check_same_thread, # factory, cached_statements. Do we really need to though? _options = _get_options(ret) database = _options.get('database') timeout = _options.get('timeout') if not database: raise Exception( 'sqlite3 config option "sqlite3.database" is missing') if not timeout: raise Exception( 'sqlite3 config option "sqlite3.timeout" is missing') log.debug('Connecting the sqlite3 database: %s timeout: %s', database, timeout) conn = sqlite3.connect(database, timeout=float(timeout)) return conn
python
def _get_conn(ret=None): ''' Return a sqlite3 database connection ''' # Possible todo: support detect_types, isolation_level, check_same_thread, # factory, cached_statements. Do we really need to though? _options = _get_options(ret) database = _options.get('database') timeout = _options.get('timeout') if not database: raise Exception( 'sqlite3 config option "sqlite3.database" is missing') if not timeout: raise Exception( 'sqlite3 config option "sqlite3.timeout" is missing') log.debug('Connecting the sqlite3 database: %s timeout: %s', database, timeout) conn = sqlite3.connect(database, timeout=float(timeout)) return conn
[ "def", "_get_conn", "(", "ret", "=", "None", ")", ":", "# Possible todo: support detect_types, isolation_level, check_same_thread,", "# factory, cached_statements. Do we really need to though?", "_options", "=", "_get_options", "(", "ret", ")", "database", "=", "_options", ".",...
Return a sqlite3 database connection
[ "Return", "a", "sqlite3", "database", "connection" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/sqlite3_return.py#L131-L149
train
saltstack/salt
salt/returners/sqlite3_return.py
returner
def returner(ret): ''' Insert minion return data into the sqlite3 database ''' log.debug('sqlite3 returner <returner> called with data: %s', ret) conn = _get_conn(ret) cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, id, fun_args, date, full_ret, success) VALUES (:fun, :jid, :id, :fun_args, :date, :full_ret, :success)''' cur.execute(sql, {'fun': ret['fun'], 'jid': ret['jid'], 'id': ret['id'], 'fun_args': six.text_type(ret['fun_args']) if ret.get('fun_args') else None, 'date': six.text_type(datetime.datetime.now()), 'full_ret': salt.utils.json.dumps(ret['return']), 'success': ret.get('success', '')}) _close_conn(conn)
python
def returner(ret): ''' Insert minion return data into the sqlite3 database ''' log.debug('sqlite3 returner <returner> called with data: %s', ret) conn = _get_conn(ret) cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, id, fun_args, date, full_ret, success) VALUES (:fun, :jid, :id, :fun_args, :date, :full_ret, :success)''' cur.execute(sql, {'fun': ret['fun'], 'jid': ret['jid'], 'id': ret['id'], 'fun_args': six.text_type(ret['fun_args']) if ret.get('fun_args') else None, 'date': six.text_type(datetime.datetime.now()), 'full_ret': salt.utils.json.dumps(ret['return']), 'success': ret.get('success', '')}) _close_conn(conn)
[ "def", "returner", "(", "ret", ")", ":", "log", ".", "debug", "(", "'sqlite3 returner <returner> called with data: %s'", ",", "ret", ")", "conn", "=", "_get_conn", "(", "ret", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "sql", "=", "'''INSERT INTO salt...
Insert minion return data into the sqlite3 database
[ "Insert", "minion", "return", "data", "into", "the", "sqlite3", "database" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/sqlite3_return.py#L161-L179
train
saltstack/salt
salt/returners/sqlite3_return.py
save_load
def save_load(jid, load, minions=None): ''' Save the load to the specified jid ''' log.debug('sqlite3 returner <save_load> called jid: %s load: %s', jid, load) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''INSERT INTO jids (jid, load) VALUES (:jid, :load)''' cur.execute(sql, {'jid': jid, 'load': salt.utils.json.dumps(load)}) _close_conn(conn)
python
def save_load(jid, load, minions=None): ''' Save the load to the specified jid ''' log.debug('sqlite3 returner <save_load> called jid: %s load: %s', jid, load) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''INSERT INTO jids (jid, load) VALUES (:jid, :load)''' cur.execute(sql, {'jid': jid, 'load': salt.utils.json.dumps(load)}) _close_conn(conn)
[ "def", "save_load", "(", "jid", ",", "load", ",", "minions", "=", "None", ")", ":", "log", ".", "debug", "(", "'sqlite3 returner <save_load> called jid: %s load: %s'", ",", "jid", ",", "load", ")", "conn", "=", "_get_conn", "(", "ret", "=", "None", ")", "c...
Save the load to the specified jid
[ "Save", "the", "load", "to", "the", "specified", "jid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/sqlite3_return.py#L182-L193
train
saltstack/salt
salt/returners/sqlite3_return.py
get_load
def get_load(jid): ''' Return the load from a specified jid ''' log.debug('sqlite3 returner <get_load> called jid: %s', jid) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT load FROM jids WHERE jid = :jid''' cur.execute(sql, {'jid': jid}) data = cur.fetchone() if data: return salt.utils.json.loads(data[0].encode()) _close_conn(conn) return {}
python
def get_load(jid): ''' Return the load from a specified jid ''' log.debug('sqlite3 returner <get_load> called jid: %s', jid) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT load FROM jids WHERE jid = :jid''' cur.execute(sql, {'jid': jid}) data = cur.fetchone() if data: return salt.utils.json.loads(data[0].encode()) _close_conn(conn) return {}
[ "def", "get_load", "(", "jid", ")", ":", "log", ".", "debug", "(", "'sqlite3 returner <get_load> called jid: %s'", ",", "jid", ")", "conn", "=", "_get_conn", "(", "ret", "=", "None", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "sql", "=", "'''SELEC...
Return the load from a specified jid
[ "Return", "the", "load", "from", "a", "specified", "jid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/sqlite3_return.py#L203-L217
train
saltstack/salt
salt/returners/sqlite3_return.py
get_jid
def get_jid(jid): ''' Return the information returned from a specified jid ''' log.debug('sqlite3 returner <get_jid> called jid: %s', jid) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT id, full_ret FROM salt_returns WHERE jid = :jid''' cur.execute(sql, {'jid': jid}) data = cur.fetchone() log.debug('query result: %s', data) ret = {} if data and len(data) > 1: ret = {six.text_type(data[0]): {'return': salt.utils.json.loads(data[1])}} log.debug('ret: %s', ret) _close_conn(conn) return ret
python
def get_jid(jid): ''' Return the information returned from a specified jid ''' log.debug('sqlite3 returner <get_jid> called jid: %s', jid) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT id, full_ret FROM salt_returns WHERE jid = :jid''' cur.execute(sql, {'jid': jid}) data = cur.fetchone() log.debug('query result: %s', data) ret = {} if data and len(data) > 1: ret = {six.text_type(data[0]): {'return': salt.utils.json.loads(data[1])}} log.debug('ret: %s', ret) _close_conn(conn) return ret
[ "def", "get_jid", "(", "jid", ")", ":", "log", ".", "debug", "(", "'sqlite3 returner <get_jid> called jid: %s'", ",", "jid", ")", "conn", "=", "_get_conn", "(", "ret", "=", "None", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "sql", "=", "'''SELECT ...
Return the information returned from a specified jid
[ "Return", "the", "information", "returned", "from", "a", "specified", "jid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/sqlite3_return.py#L220-L237
train
saltstack/salt
salt/returners/sqlite3_return.py
get_fun
def get_fun(fun): ''' Return a dict of the last function called for all minions ''' log.debug('sqlite3 returner <get_fun> called fun: %s', fun) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT s.id, s.full_ret, s.jid FROM salt_returns s JOIN ( SELECT MAX(jid) AS jid FROM salt_returns GROUP BY fun, id) max ON s.jid = max.jid WHERE s.fun = :fun ''' cur.execute(sql, {'fun': fun}) data = cur.fetchall() ret = {} if data: # Pop the jid off the list since it is not # needed and I am trying to get a perfect # pylint score :-) data.pop() for minion, ret in data: ret[minion] = salt.utils.json.loads(ret) _close_conn(conn) return ret
python
def get_fun(fun): ''' Return a dict of the last function called for all minions ''' log.debug('sqlite3 returner <get_fun> called fun: %s', fun) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT s.id, s.full_ret, s.jid FROM salt_returns s JOIN ( SELECT MAX(jid) AS jid FROM salt_returns GROUP BY fun, id) max ON s.jid = max.jid WHERE s.fun = :fun ''' cur.execute(sql, {'fun': fun}) data = cur.fetchall() ret = {} if data: # Pop the jid off the list since it is not # needed and I am trying to get a perfect # pylint score :-) data.pop() for minion, ret in data: ret[minion] = salt.utils.json.loads(ret) _close_conn(conn) return ret
[ "def", "get_fun", "(", "fun", ")", ":", "log", ".", "debug", "(", "'sqlite3 returner <get_fun> called fun: %s'", ",", "fun", ")", "conn", "=", "_get_conn", "(", "ret", "=", "None", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "sql", "=", "'''SELECT ...
Return a dict of the last function called for all minions
[ "Return", "a", "dict", "of", "the", "last", "function", "called", "for", "all", "minions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/sqlite3_return.py#L240-L265
train
saltstack/salt
salt/returners/sqlite3_return.py
get_minions
def get_minions(): ''' Return a list of minions ''' log.debug('sqlite3 returner <get_minions> called') conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT DISTINCT id FROM salt_returns''' cur.execute(sql) data = cur.fetchall() ret = [] for minion in data: ret.append(minion[0]) _close_conn(conn) return ret
python
def get_minions(): ''' Return a list of minions ''' log.debug('sqlite3 returner <get_minions> called') conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT DISTINCT id FROM salt_returns''' cur.execute(sql) data = cur.fetchall() ret = [] for minion in data: ret.append(minion[0]) _close_conn(conn) return ret
[ "def", "get_minions", "(", ")", ":", "log", ".", "debug", "(", "'sqlite3 returner <get_minions> called'", ")", "conn", "=", "_get_conn", "(", "ret", "=", "None", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "sql", "=", "'''SELECT DISTINCT id FROM salt_ret...
Return a list of minions
[ "Return", "a", "list", "of", "minions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/sqlite3_return.py#L285-L299
train
saltstack/salt
salt/modules/git.py
_check_worktree_support
def _check_worktree_support(failhard=True): ''' Ensure that we don't try to operate on worktrees in git < 2.5.0. ''' git_version = version(versioninfo=False) if _LooseVersion(git_version) < _LooseVersion('2.5.0'): if failhard: raise CommandExecutionError( 'Worktrees are only supported in git 2.5.0 and newer ' '(detected git version: ' + git_version + ')' ) return False return True
python
def _check_worktree_support(failhard=True): ''' Ensure that we don't try to operate on worktrees in git < 2.5.0. ''' git_version = version(versioninfo=False) if _LooseVersion(git_version) < _LooseVersion('2.5.0'): if failhard: raise CommandExecutionError( 'Worktrees are only supported in git 2.5.0 and newer ' '(detected git version: ' + git_version + ')' ) return False return True
[ "def", "_check_worktree_support", "(", "failhard", "=", "True", ")", ":", "git_version", "=", "version", "(", "versioninfo", "=", "False", ")", "if", "_LooseVersion", "(", "git_version", ")", "<", "_LooseVersion", "(", "'2.5.0'", ")", ":", "if", "failhard", ...
Ensure that we don't try to operate on worktrees in git < 2.5.0.
[ "Ensure", "that", "we", "don", "t", "try", "to", "operate", "on", "worktrees", "in", "git", "<", "2", ".", "5", ".", "0", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L48-L60
train
saltstack/salt
salt/modules/git.py
_config_getter
def _config_getter(get_opt, key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Common code for config.get_* functions, builds and runs the git CLI command and returns the result dict for the calling function to parse. ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) global_ = kwargs.pop('global', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if cwd is None: if not global_: raise SaltInvocationError( '\'cwd\' argument required unless global=True' ) else: cwd = _expand_path(cwd, user) if get_opt == '--get-regexp': if value_regex is not None \ and not isinstance(value_regex, six.string_types): value_regex = six.text_type(value_regex) else: # Ignore value_regex value_regex = None command = ['git', 'config'] command.extend(_which_git_config(global_, cwd, user, password, output_encoding=output_encoding)) command.append(get_opt) command.append(key) if value_regex is not None: command.append(value_regex) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, failhard=False, output_encoding=output_encoding)
python
def _config_getter(get_opt, key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Common code for config.get_* functions, builds and runs the git CLI command and returns the result dict for the calling function to parse. ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) global_ = kwargs.pop('global', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if cwd is None: if not global_: raise SaltInvocationError( '\'cwd\' argument required unless global=True' ) else: cwd = _expand_path(cwd, user) if get_opt == '--get-regexp': if value_regex is not None \ and not isinstance(value_regex, six.string_types): value_regex = six.text_type(value_regex) else: # Ignore value_regex value_regex = None command = ['git', 'config'] command.extend(_which_git_config(global_, cwd, user, password, output_encoding=output_encoding)) command.append(get_opt) command.append(key) if value_regex is not None: command.append(value_regex) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, failhard=False, output_encoding=output_encoding)
[ "def", "_config_getter", "(", "get_opt", ",", "key", ",", "value_regex", "=", "None", ",", "cwd", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ",", "*", "...
Common code for config.get_* functions, builds and runs the git CLI command and returns the result dict for the calling function to parse.
[ "Common", "code", "for", "config", ".", "get_", "*", "functions", "builds", "and", "runs", "the", "git", "CLI", "command", "and", "returns", "the", "result", "dict", "for", "the", "calling", "function", "to", "parse", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L63-L110
train
saltstack/salt
salt/modules/git.py
_expand_path
def _expand_path(cwd, user): ''' Expand home directory ''' try: to_expand = '~' + user if user else '~' except TypeError: # Users should never be numeric but if we don't account for this then # we're going to get a traceback if someone passes this invalid input. to_expand = '~' + six.text_type(user) if user else '~' try: return os.path.join(os.path.expanduser(to_expand), cwd) except AttributeError: return os.path.join(os.path.expanduser(to_expand), six.text_type(cwd))
python
def _expand_path(cwd, user): ''' Expand home directory ''' try: to_expand = '~' + user if user else '~' except TypeError: # Users should never be numeric but if we don't account for this then # we're going to get a traceback if someone passes this invalid input. to_expand = '~' + six.text_type(user) if user else '~' try: return os.path.join(os.path.expanduser(to_expand), cwd) except AttributeError: return os.path.join(os.path.expanduser(to_expand), six.text_type(cwd))
[ "def", "_expand_path", "(", "cwd", ",", "user", ")", ":", "try", ":", "to_expand", "=", "'~'", "+", "user", "if", "user", "else", "'~'", "except", "TypeError", ":", "# Users should never be numeric but if we don't account for this then", "# we're going to get a tracebac...
Expand home directory
[ "Expand", "home", "directory" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L113-L126
train
saltstack/salt
salt/modules/git.py
_path_is_executable_others
def _path_is_executable_others(path): ''' Check every part of path for executable permission ''' prevpath = None while path and path != prevpath: try: if not os.stat(path).st_mode & stat.S_IXOTH: return False except OSError: return False prevpath = path path, _ = os.path.split(path) return True
python
def _path_is_executable_others(path): ''' Check every part of path for executable permission ''' prevpath = None while path and path != prevpath: try: if not os.stat(path).st_mode & stat.S_IXOTH: return False except OSError: return False prevpath = path path, _ = os.path.split(path) return True
[ "def", "_path_is_executable_others", "(", "path", ")", ":", "prevpath", "=", "None", "while", "path", "and", "path", "!=", "prevpath", ":", "try", ":", "if", "not", "os", ".", "stat", "(", "path", ")", ".", "st_mode", "&", "stat", ".", "S_IXOTH", ":", ...
Check every part of path for executable permission
[ "Check", "every", "part", "of", "path", "for", "executable", "permission" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L129-L142
train
saltstack/salt
salt/modules/git.py
_format_opts
def _format_opts(opts): ''' Common code to inspect opts and split them if necessary ''' if opts is None: return [] elif isinstance(opts, list): new_opts = [] for item in opts: if isinstance(item, six.string_types): new_opts.append(item) else: new_opts.append(six.text_type(item)) return new_opts else: if not isinstance(opts, six.string_types): opts = [six.text_type(opts)] else: opts = salt.utils.args.shlex_split(opts) opts = salt.utils.data.decode(opts) try: if opts[-1] == '--': # Strip the '--' if it was passed at the end of the opts string, # it'll be added back (if necessary) in the calling function. # Putting this check here keeps it from having to be repeated every # time _format_opts() is invoked. return opts[:-1] except IndexError: pass return opts
python
def _format_opts(opts): ''' Common code to inspect opts and split them if necessary ''' if opts is None: return [] elif isinstance(opts, list): new_opts = [] for item in opts: if isinstance(item, six.string_types): new_opts.append(item) else: new_opts.append(six.text_type(item)) return new_opts else: if not isinstance(opts, six.string_types): opts = [six.text_type(opts)] else: opts = salt.utils.args.shlex_split(opts) opts = salt.utils.data.decode(opts) try: if opts[-1] == '--': # Strip the '--' if it was passed at the end of the opts string, # it'll be added back (if necessary) in the calling function. # Putting this check here keeps it from having to be repeated every # time _format_opts() is invoked. return opts[:-1] except IndexError: pass return opts
[ "def", "_format_opts", "(", "opts", ")", ":", "if", "opts", "is", "None", ":", "return", "[", "]", "elif", "isinstance", "(", "opts", ",", "list", ")", ":", "new_opts", "=", "[", "]", "for", "item", "in", "opts", ":", "if", "isinstance", "(", "item...
Common code to inspect opts and split them if necessary
[ "Common", "code", "to", "inspect", "opts", "and", "split", "them", "if", "necessary" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L145-L174
train
saltstack/salt
salt/modules/git.py
_format_git_opts
def _format_git_opts(opts): ''' Do a version check and make sure that the installed version of git can support git -c ''' if opts: version_ = version(versioninfo=False) if _LooseVersion(version_) < _LooseVersion('1.7.2'): raise SaltInvocationError( 'git_opts is only supported for git versions >= 1.7.2 ' '(detected: {0})'.format(version_) ) return _format_opts(opts)
python
def _format_git_opts(opts): ''' Do a version check and make sure that the installed version of git can support git -c ''' if opts: version_ = version(versioninfo=False) if _LooseVersion(version_) < _LooseVersion('1.7.2'): raise SaltInvocationError( 'git_opts is only supported for git versions >= 1.7.2 ' '(detected: {0})'.format(version_) ) return _format_opts(opts)
[ "def", "_format_git_opts", "(", "opts", ")", ":", "if", "opts", ":", "version_", "=", "version", "(", "versioninfo", "=", "False", ")", "if", "_LooseVersion", "(", "version_", ")", "<", "_LooseVersion", "(", "'1.7.2'", ")", ":", "raise", "SaltInvocationError...
Do a version check and make sure that the installed version of git can support git -c
[ "Do", "a", "version", "check", "and", "make", "sure", "that", "the", "installed", "version", "of", "git", "can", "support", "git", "-", "c" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L177-L189
train
saltstack/salt
salt/modules/git.py
_find_ssh_exe
def _find_ssh_exe(): ''' Windows only: search for Git's bundled ssh.exe in known locations ''' # Known locations for Git's ssh.exe in Windows globmasks = [os.path.join(os.getenv('SystemDrive'), os.sep, 'Program Files*', 'Git', 'usr', 'bin', 'ssh.exe'), os.path.join(os.getenv('SystemDrive'), os.sep, 'Program Files*', 'Git', 'bin', 'ssh.exe')] for globmask in globmasks: ssh_exe = glob.glob(globmask) if ssh_exe and os.path.isfile(ssh_exe[0]): ret = ssh_exe[0] break else: ret = None return ret
python
def _find_ssh_exe(): ''' Windows only: search for Git's bundled ssh.exe in known locations ''' # Known locations for Git's ssh.exe in Windows globmasks = [os.path.join(os.getenv('SystemDrive'), os.sep, 'Program Files*', 'Git', 'usr', 'bin', 'ssh.exe'), os.path.join(os.getenv('SystemDrive'), os.sep, 'Program Files*', 'Git', 'bin', 'ssh.exe')] for globmask in globmasks: ssh_exe = glob.glob(globmask) if ssh_exe and os.path.isfile(ssh_exe[0]): ret = ssh_exe[0] break else: ret = None return ret
[ "def", "_find_ssh_exe", "(", ")", ":", "# Known locations for Git's ssh.exe in Windows", "globmasks", "=", "[", "os", ".", "path", ".", "join", "(", "os", ".", "getenv", "(", "'SystemDrive'", ")", ",", "os", ".", "sep", ",", "'Program Files*'", ",", "'Git'", ...
Windows only: search for Git's bundled ssh.exe in known locations
[ "Windows", "only", ":", "search", "for", "Git", "s", "bundled", "ssh", ".", "exe", "in", "known", "locations" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L192-L211
train
saltstack/salt
salt/modules/git.py
_git_run
def _git_run(command, cwd=None, user=None, password=None, identity=None, ignore_retcode=False, failhard=True, redirect_stderr=False, saltenv='base', output_encoding=None, **kwargs): ''' simple, throw an exception with the error message on an error return code. this function may be moved to the command module, spliced with 'cmd.run_all', and used as an alternative to 'cmd.run_all'. Some commands don't return proper retcodes, so this can't replace 'cmd.run_all'. ''' env = {} if identity: _salt_cli = __opts__.get('__cli', '') errors = [] missing_keys = [] # if the statefile provides multiple identities, they need to be tried # (but also allow a string instead of a list) if not isinstance(identity, list): # force it into a list identity = [identity] # try each of the identities, independently tmp_identity_file = None for id_file in identity: if 'salt://' in id_file: with salt.utils.files.set_umask(0o077): tmp_identity_file = salt.utils.files.mkstemp() _id_file = id_file id_file = __salt__['cp.get_file'](id_file, tmp_identity_file, saltenv) if not id_file: log.error('identity %s does not exist.', _id_file) __salt__['file.remove'](tmp_identity_file) continue else: if user: os.chown(id_file, __salt__['file.user_to_uid'](user), -1) else: if not __salt__['file.file_exists'](id_file): missing_keys.append(id_file) log.error('identity %s does not exist.', id_file) continue env = { 'GIT_IDENTITY': id_file } # copy wrapper to area accessible by ``runas`` user # currently no support in windows for wrapping git ssh ssh_id_wrapper = os.path.abspath(os.path.join( salt.utils.templates.TEMPLATE_DIRNAME, 'git/ssh-id-wrapper' )) tmp_ssh_wrapper = None if salt.utils.platform.is_windows(): ssh_exe = _find_ssh_exe() if ssh_exe is None: raise CommandExecutionError( 'Failed to find ssh.exe, unable to use identity file' ) env['GIT_SSH_EXE'] = ssh_exe # Use the windows batch file instead of the bourne shell script ssh_id_wrapper += '.bat' env['GIT_SSH'] = ssh_id_wrapper elif not user or _path_is_executable_others(ssh_id_wrapper): env['GIT_SSH'] = ssh_id_wrapper else: tmp_ssh_wrapper = salt.utils.files.mkstemp() salt.utils.files.copyfile(ssh_id_wrapper, tmp_ssh_wrapper) os.chmod(tmp_ssh_wrapper, 0o500) os.chown(tmp_ssh_wrapper, __salt__['file.user_to_uid'](user), -1) env['GIT_SSH'] = tmp_ssh_wrapper if 'salt-call' not in _salt_cli \ and __utils__['ssh.key_is_encrypted'](id_file): errors.append( 'Identity file {0} is passphrase-protected and cannot be ' 'used in a non-interactive command. Using salt-call from ' 'the minion will allow a passphrase-protected key to be ' 'used.'.format(id_file) ) continue log.info( 'Attempting git authentication using identity file %s', id_file ) try: result = __salt__['cmd.run_all']( command, cwd=cwd, runas=user, password=password, env=env, python_shell=False, log_callback=salt.utils.url.redact_http_basic_auth, ignore_retcode=ignore_retcode, redirect_stderr=redirect_stderr, output_encoding=output_encoding, **kwargs) finally: if tmp_ssh_wrapper: # Cleanup the temporary ssh wrapper file try: __salt__['file.remove'](tmp_ssh_wrapper) log.debug('Removed ssh wrapper file %s', tmp_ssh_wrapper) except AttributeError: # No wrapper was used pass except (SaltInvocationError, CommandExecutionError) as exc: log.warning( 'Failed to remove ssh wrapper file %s: %s', tmp_ssh_wrapper, exc ) if tmp_identity_file: # Cleanup the temporary identity file try: __salt__['file.remove'](tmp_identity_file) log.debug('Removed identity file %s', tmp_identity_file) except AttributeError: # No identify file was used pass except (SaltInvocationError, CommandExecutionError) as exc: log.warning( 'Failed to remove identity file %s: %s', tmp_identity_file, exc ) # If the command was successful, no need to try additional IDs if result['retcode'] == 0: return result else: err = result['stdout' if redirect_stderr else 'stderr'] if err: errors.append(salt.utils.url.redact_http_basic_auth(err)) # We've tried all IDs and still haven't passed, so error out if failhard: msg = ( 'Unable to authenticate using identity file:\n\n{0}'.format( '\n'.join(errors) ) ) if missing_keys: if errors: msg += '\n\n' msg += ( 'The following identity file(s) were not found: {0}' .format(', '.join(missing_keys)) ) raise CommandExecutionError(msg) return result else: result = __salt__['cmd.run_all']( command, cwd=cwd, runas=user, password=password, env=env, python_shell=False, log_callback=salt.utils.url.redact_http_basic_auth, ignore_retcode=ignore_retcode, redirect_stderr=redirect_stderr, output_encoding=output_encoding, **kwargs) if result['retcode'] == 0: return result else: if failhard: gitcommand = ' '.join(command) \ if isinstance(command, list) \ else command msg = 'Command \'{0}\' failed'.format( salt.utils.url.redact_http_basic_auth(gitcommand) ) err = result['stdout' if redirect_stderr else 'stderr'] if err: msg += ': {0}'.format( salt.utils.url.redact_http_basic_auth(err) ) raise CommandExecutionError(msg) return result
python
def _git_run(command, cwd=None, user=None, password=None, identity=None, ignore_retcode=False, failhard=True, redirect_stderr=False, saltenv='base', output_encoding=None, **kwargs): ''' simple, throw an exception with the error message on an error return code. this function may be moved to the command module, spliced with 'cmd.run_all', and used as an alternative to 'cmd.run_all'. Some commands don't return proper retcodes, so this can't replace 'cmd.run_all'. ''' env = {} if identity: _salt_cli = __opts__.get('__cli', '') errors = [] missing_keys = [] # if the statefile provides multiple identities, they need to be tried # (but also allow a string instead of a list) if not isinstance(identity, list): # force it into a list identity = [identity] # try each of the identities, independently tmp_identity_file = None for id_file in identity: if 'salt://' in id_file: with salt.utils.files.set_umask(0o077): tmp_identity_file = salt.utils.files.mkstemp() _id_file = id_file id_file = __salt__['cp.get_file'](id_file, tmp_identity_file, saltenv) if not id_file: log.error('identity %s does not exist.', _id_file) __salt__['file.remove'](tmp_identity_file) continue else: if user: os.chown(id_file, __salt__['file.user_to_uid'](user), -1) else: if not __salt__['file.file_exists'](id_file): missing_keys.append(id_file) log.error('identity %s does not exist.', id_file) continue env = { 'GIT_IDENTITY': id_file } # copy wrapper to area accessible by ``runas`` user # currently no support in windows for wrapping git ssh ssh_id_wrapper = os.path.abspath(os.path.join( salt.utils.templates.TEMPLATE_DIRNAME, 'git/ssh-id-wrapper' )) tmp_ssh_wrapper = None if salt.utils.platform.is_windows(): ssh_exe = _find_ssh_exe() if ssh_exe is None: raise CommandExecutionError( 'Failed to find ssh.exe, unable to use identity file' ) env['GIT_SSH_EXE'] = ssh_exe # Use the windows batch file instead of the bourne shell script ssh_id_wrapper += '.bat' env['GIT_SSH'] = ssh_id_wrapper elif not user or _path_is_executable_others(ssh_id_wrapper): env['GIT_SSH'] = ssh_id_wrapper else: tmp_ssh_wrapper = salt.utils.files.mkstemp() salt.utils.files.copyfile(ssh_id_wrapper, tmp_ssh_wrapper) os.chmod(tmp_ssh_wrapper, 0o500) os.chown(tmp_ssh_wrapper, __salt__['file.user_to_uid'](user), -1) env['GIT_SSH'] = tmp_ssh_wrapper if 'salt-call' not in _salt_cli \ and __utils__['ssh.key_is_encrypted'](id_file): errors.append( 'Identity file {0} is passphrase-protected and cannot be ' 'used in a non-interactive command. Using salt-call from ' 'the minion will allow a passphrase-protected key to be ' 'used.'.format(id_file) ) continue log.info( 'Attempting git authentication using identity file %s', id_file ) try: result = __salt__['cmd.run_all']( command, cwd=cwd, runas=user, password=password, env=env, python_shell=False, log_callback=salt.utils.url.redact_http_basic_auth, ignore_retcode=ignore_retcode, redirect_stderr=redirect_stderr, output_encoding=output_encoding, **kwargs) finally: if tmp_ssh_wrapper: # Cleanup the temporary ssh wrapper file try: __salt__['file.remove'](tmp_ssh_wrapper) log.debug('Removed ssh wrapper file %s', tmp_ssh_wrapper) except AttributeError: # No wrapper was used pass except (SaltInvocationError, CommandExecutionError) as exc: log.warning( 'Failed to remove ssh wrapper file %s: %s', tmp_ssh_wrapper, exc ) if tmp_identity_file: # Cleanup the temporary identity file try: __salt__['file.remove'](tmp_identity_file) log.debug('Removed identity file %s', tmp_identity_file) except AttributeError: # No identify file was used pass except (SaltInvocationError, CommandExecutionError) as exc: log.warning( 'Failed to remove identity file %s: %s', tmp_identity_file, exc ) # If the command was successful, no need to try additional IDs if result['retcode'] == 0: return result else: err = result['stdout' if redirect_stderr else 'stderr'] if err: errors.append(salt.utils.url.redact_http_basic_auth(err)) # We've tried all IDs and still haven't passed, so error out if failhard: msg = ( 'Unable to authenticate using identity file:\n\n{0}'.format( '\n'.join(errors) ) ) if missing_keys: if errors: msg += '\n\n' msg += ( 'The following identity file(s) were not found: {0}' .format(', '.join(missing_keys)) ) raise CommandExecutionError(msg) return result else: result = __salt__['cmd.run_all']( command, cwd=cwd, runas=user, password=password, env=env, python_shell=False, log_callback=salt.utils.url.redact_http_basic_auth, ignore_retcode=ignore_retcode, redirect_stderr=redirect_stderr, output_encoding=output_encoding, **kwargs) if result['retcode'] == 0: return result else: if failhard: gitcommand = ' '.join(command) \ if isinstance(command, list) \ else command msg = 'Command \'{0}\' failed'.format( salt.utils.url.redact_http_basic_auth(gitcommand) ) err = result['stdout' if redirect_stderr else 'stderr'] if err: msg += ': {0}'.format( salt.utils.url.redact_http_basic_auth(err) ) raise CommandExecutionError(msg) return result
[ "def", "_git_run", "(", "command", ",", "cwd", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "None", ",", "ignore_retcode", "=", "False", ",", "failhard", "=", "True", ",", "redirect_stderr", "=", "False", "...
simple, throw an exception with the error message on an error return code. this function may be moved to the command module, spliced with 'cmd.run_all', and used as an alternative to 'cmd.run_all'. Some commands don't return proper retcodes, so this can't replace 'cmd.run_all'.
[ "simple", "throw", "an", "exception", "with", "the", "error", "message", "on", "an", "error", "return", "code", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L214-L404
train
saltstack/salt
salt/modules/git.py
_get_toplevel
def _get_toplevel(path, user=None, password=None, output_encoding=None): ''' Use git rev-parse to return the top level of a repo ''' return _git_run( ['git', 'rev-parse', '--show-toplevel'], cwd=path, user=user, password=password, output_encoding=output_encoding)['stdout']
python
def _get_toplevel(path, user=None, password=None, output_encoding=None): ''' Use git rev-parse to return the top level of a repo ''' return _git_run( ['git', 'rev-parse', '--show-toplevel'], cwd=path, user=user, password=password, output_encoding=output_encoding)['stdout']
[ "def", "_get_toplevel", "(", "path", ",", "user", "=", "None", ",", "password", "=", "None", ",", "output_encoding", "=", "None", ")", ":", "return", "_git_run", "(", "[", "'git'", ",", "'rev-parse'", ",", "'--show-toplevel'", "]", ",", "cwd", "=", "path...
Use git rev-parse to return the top level of a repo
[ "Use", "git", "rev", "-", "parse", "to", "return", "the", "top", "level", "of", "a", "repo" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L407-L416
train
saltstack/salt
salt/modules/git.py
_git_config
def _git_config(cwd, user, password, output_encoding=None): ''' Helper to retrieve git config options ''' contextkey = 'git.config.' + cwd if contextkey not in __context__: git_dir = rev_parse(cwd, opts=['--git-dir'], user=user, password=password, ignore_retcode=True, output_encoding=output_encoding) if not os.path.isabs(git_dir): paths = (cwd, git_dir, 'config') else: paths = (git_dir, 'config') __context__[contextkey] = os.path.join(*paths) return __context__[contextkey]
python
def _git_config(cwd, user, password, output_encoding=None): ''' Helper to retrieve git config options ''' contextkey = 'git.config.' + cwd if contextkey not in __context__: git_dir = rev_parse(cwd, opts=['--git-dir'], user=user, password=password, ignore_retcode=True, output_encoding=output_encoding) if not os.path.isabs(git_dir): paths = (cwd, git_dir, 'config') else: paths = (git_dir, 'config') __context__[contextkey] = os.path.join(*paths) return __context__[contextkey]
[ "def", "_git_config", "(", "cwd", ",", "user", ",", "password", ",", "output_encoding", "=", "None", ")", ":", "contextkey", "=", "'git.config.'", "+", "cwd", "if", "contextkey", "not", "in", "__context__", ":", "git_dir", "=", "rev_parse", "(", "cwd", ","...
Helper to retrieve git config options
[ "Helper", "to", "retrieve", "git", "config", "options" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L419-L436
train
saltstack/salt
salt/modules/git.py
_which_git_config
def _which_git_config(global_, cwd, user, password, output_encoding=None): ''' Based on whether global or local config is desired, return a list of CLI args to include in the git config command. ''' if global_: return ['--global'] version_ = _LooseVersion(version(versioninfo=False)) if version_ >= _LooseVersion('1.7.10.2'): # --local added in 1.7.10.2 return ['--local'] else: # For earlier versions, need to specify the path to the git config file return ['--file', _git_config(cwd, user, password, output_encoding=output_encoding)]
python
def _which_git_config(global_, cwd, user, password, output_encoding=None): ''' Based on whether global or local config is desired, return a list of CLI args to include in the git config command. ''' if global_: return ['--global'] version_ = _LooseVersion(version(versioninfo=False)) if version_ >= _LooseVersion('1.7.10.2'): # --local added in 1.7.10.2 return ['--local'] else: # For earlier versions, need to specify the path to the git config file return ['--file', _git_config(cwd, user, password, output_encoding=output_encoding)]
[ "def", "_which_git_config", "(", "global_", ",", "cwd", ",", "user", ",", "password", ",", "output_encoding", "=", "None", ")", ":", "if", "global_", ":", "return", "[", "'--global'", "]", "version_", "=", "_LooseVersion", "(", "version", "(", "versioninfo",...
Based on whether global or local config is desired, return a list of CLI args to include in the git config command.
[ "Based", "on", "whether", "global", "or", "local", "config", "is", "desired", "return", "a", "list", "of", "CLI", "args", "to", "include", "in", "the", "git", "config", "command", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L439-L453
train
saltstack/salt
salt/modules/git.py
add
def add(cwd, filename, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionchanged:: 2015.8.0 The ``--verbose`` command line argument is now implied Interface to `git-add(1)`_ cwd The path to the git checkout filename The location of the file/directory to add, relative to ``cwd`` opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``add`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-add(1)`: http://git-scm.com/docs/git-add CLI Examples: .. code-block:: bash salt myminion git.add /path/to/repo foo/bar.py salt myminion git.add /path/to/repo foo/bar.py opts='--dry-run' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.extend(['add', '--verbose']) command.extend( [x for x in _format_opts(opts) if x not in ('-v', '--verbose')] ) command.extend(['--', filename]) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def add(cwd, filename, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionchanged:: 2015.8.0 The ``--verbose`` command line argument is now implied Interface to `git-add(1)`_ cwd The path to the git checkout filename The location of the file/directory to add, relative to ``cwd`` opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``add`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-add(1)`: http://git-scm.com/docs/git-add CLI Examples: .. code-block:: bash salt myminion git.add /path/to/repo foo/bar.py salt myminion git.add /path/to/repo foo/bar.py opts='--dry-run' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.extend(['add', '--verbose']) command.extend( [x for x in _format_opts(opts) if x not in ('-v', '--verbose')] ) command.extend(['--', filename]) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "add", "(", "cwd", ",", "filename", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "...
.. versionchanged:: 2015.8.0 The ``--verbose`` command line argument is now implied Interface to `git-add(1)`_ cwd The path to the git checkout filename The location of the file/directory to add, relative to ``cwd`` opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``add`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-add(1)`: http://git-scm.com/docs/git-add CLI Examples: .. code-block:: bash salt myminion git.add /path/to/repo foo/bar.py salt myminion git.add /path/to/repo foo/bar.py opts='--dry-run'
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "0", "The", "--", "verbose", "command", "line", "argument", "is", "now", "implied" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L456-L543
train
saltstack/salt
salt/modules/git.py
archive
def archive(cwd, output, rev='HEAD', prefix=None, git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionchanged:: 2015.8.0 Returns ``True`` if successful, raises an error if not. Interface to `git-archive(1)`_, exports a tarball/zip file of the repository cwd The path to be archived .. note:: ``git archive`` permits a partial archive to be created. Thus, this path does not need to be the root of the git repository. Only the files within the directory specified by ``cwd`` (and its subdirectories) will be in the resulting archive. For example, if there is a git checkout at ``/tmp/foo``, then passing ``/tmp/foo/bar`` as the ``cwd`` will result in just the files underneath ``/tmp/foo/bar`` to be exported as an archive. output The path of the archive to be created overwrite : False Unless set to ``True``, Salt will over overwrite an existing archive at the path specified by the ``output`` argument. .. versionadded:: 2015.8.0 rev : HEAD The revision from which to create the archive format Manually specify the file format of the resulting archive. This argument can be omitted, and ``git archive`` will attempt to guess the archive type (and compression) from the filename. ``zip``, ``tar``, ``tar.gz``, and ``tgz`` are extensions that are recognized automatically, and git can be configured to support other archive types with the addition of git configuration keys. See the `git-archive(1)`_ manpage explanation of the ``--format`` argument (as well as the ``CONFIGURATION`` section of the manpage) for further information. .. versionadded:: 2015.8.0 prefix Prepend ``<prefix>`` to every filename in the archive. If unspecified, the name of the directory at the top level of the repository will be used as the prefix (e.g. if ``cwd`` is set to ``/foo/bar/baz``, the prefix will be ``baz``, and the resulting archive will contain a top-level directory by that name). .. note:: The default behavior if the ``--prefix`` option for ``git archive`` is not specified is to not prepend a prefix, so Salt's behavior differs slightly from ``git archive`` in this respect. Use ``prefix=''`` to create an archive with no prefix. .. versionchanged:: 2015.8.0 The behavior of this argument has been changed slightly. As of this version, it is necessary to include the trailing slash when specifying a prefix, if the prefix is intended to create a top-level directory. git_opts Any additional options to add to git command itself (not the ``archive`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-archive(1)`: http://git-scm.com/docs/git-archive CLI Example: .. code-block:: bash salt myminion git.archive /path/to/repo /path/to/archive.tar ''' cwd = _expand_path(cwd, user) output = _expand_path(output, user) # Sanitize kwargs and make sure that no invalid ones were passed. This # allows us to accept 'format' as an argument to this function without # shadowing the format() global, while also not allowing unwanted arguments # to be passed. kwargs = salt.utils.args.clean_kwargs(**kwargs) format_ = kwargs.pop('format', None) if kwargs: salt.utils.args.invalid_kwargs(kwargs) command = ['git'] + _format_git_opts(git_opts) command.append('archive') # If prefix was set to '' then we skip adding the --prefix option, but if # it was not passed (i.e. None) we use the cwd. if prefix != '': if not prefix: prefix = os.path.basename(cwd) + os.sep command.extend(['--prefix', prefix]) if format_: command.extend(['--format', format_]) command.extend(['--output', output, rev]) _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) # No output (unless --verbose is used, and we don't want all files listed # in the output in case there are thousands), so just return True. If there # was an error in the git command, it will have already raised an exception # and we will never get to this return statement. return True
python
def archive(cwd, output, rev='HEAD', prefix=None, git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionchanged:: 2015.8.0 Returns ``True`` if successful, raises an error if not. Interface to `git-archive(1)`_, exports a tarball/zip file of the repository cwd The path to be archived .. note:: ``git archive`` permits a partial archive to be created. Thus, this path does not need to be the root of the git repository. Only the files within the directory specified by ``cwd`` (and its subdirectories) will be in the resulting archive. For example, if there is a git checkout at ``/tmp/foo``, then passing ``/tmp/foo/bar`` as the ``cwd`` will result in just the files underneath ``/tmp/foo/bar`` to be exported as an archive. output The path of the archive to be created overwrite : False Unless set to ``True``, Salt will over overwrite an existing archive at the path specified by the ``output`` argument. .. versionadded:: 2015.8.0 rev : HEAD The revision from which to create the archive format Manually specify the file format of the resulting archive. This argument can be omitted, and ``git archive`` will attempt to guess the archive type (and compression) from the filename. ``zip``, ``tar``, ``tar.gz``, and ``tgz`` are extensions that are recognized automatically, and git can be configured to support other archive types with the addition of git configuration keys. See the `git-archive(1)`_ manpage explanation of the ``--format`` argument (as well as the ``CONFIGURATION`` section of the manpage) for further information. .. versionadded:: 2015.8.0 prefix Prepend ``<prefix>`` to every filename in the archive. If unspecified, the name of the directory at the top level of the repository will be used as the prefix (e.g. if ``cwd`` is set to ``/foo/bar/baz``, the prefix will be ``baz``, and the resulting archive will contain a top-level directory by that name). .. note:: The default behavior if the ``--prefix`` option for ``git archive`` is not specified is to not prepend a prefix, so Salt's behavior differs slightly from ``git archive`` in this respect. Use ``prefix=''`` to create an archive with no prefix. .. versionchanged:: 2015.8.0 The behavior of this argument has been changed slightly. As of this version, it is necessary to include the trailing slash when specifying a prefix, if the prefix is intended to create a top-level directory. git_opts Any additional options to add to git command itself (not the ``archive`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-archive(1)`: http://git-scm.com/docs/git-archive CLI Example: .. code-block:: bash salt myminion git.archive /path/to/repo /path/to/archive.tar ''' cwd = _expand_path(cwd, user) output = _expand_path(output, user) # Sanitize kwargs and make sure that no invalid ones were passed. This # allows us to accept 'format' as an argument to this function without # shadowing the format() global, while also not allowing unwanted arguments # to be passed. kwargs = salt.utils.args.clean_kwargs(**kwargs) format_ = kwargs.pop('format', None) if kwargs: salt.utils.args.invalid_kwargs(kwargs) command = ['git'] + _format_git_opts(git_opts) command.append('archive') # If prefix was set to '' then we skip adding the --prefix option, but if # it was not passed (i.e. None) we use the cwd. if prefix != '': if not prefix: prefix = os.path.basename(cwd) + os.sep command.extend(['--prefix', prefix]) if format_: command.extend(['--format', format_]) command.extend(['--output', output, rev]) _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) # No output (unless --verbose is used, and we don't want all files listed # in the output in case there are thousands), so just return True. If there # was an error in the git command, it will have already raised an exception # and we will never get to this return statement. return True
[ "def", "archive", "(", "cwd", ",", "output", ",", "rev", "=", "'HEAD'", ",", "prefix", "=", "None", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", ...
.. versionchanged:: 2015.8.0 Returns ``True`` if successful, raises an error if not. Interface to `git-archive(1)`_, exports a tarball/zip file of the repository cwd The path to be archived .. note:: ``git archive`` permits a partial archive to be created. Thus, this path does not need to be the root of the git repository. Only the files within the directory specified by ``cwd`` (and its subdirectories) will be in the resulting archive. For example, if there is a git checkout at ``/tmp/foo``, then passing ``/tmp/foo/bar`` as the ``cwd`` will result in just the files underneath ``/tmp/foo/bar`` to be exported as an archive. output The path of the archive to be created overwrite : False Unless set to ``True``, Salt will over overwrite an existing archive at the path specified by the ``output`` argument. .. versionadded:: 2015.8.0 rev : HEAD The revision from which to create the archive format Manually specify the file format of the resulting archive. This argument can be omitted, and ``git archive`` will attempt to guess the archive type (and compression) from the filename. ``zip``, ``tar``, ``tar.gz``, and ``tgz`` are extensions that are recognized automatically, and git can be configured to support other archive types with the addition of git configuration keys. See the `git-archive(1)`_ manpage explanation of the ``--format`` argument (as well as the ``CONFIGURATION`` section of the manpage) for further information. .. versionadded:: 2015.8.0 prefix Prepend ``<prefix>`` to every filename in the archive. If unspecified, the name of the directory at the top level of the repository will be used as the prefix (e.g. if ``cwd`` is set to ``/foo/bar/baz``, the prefix will be ``baz``, and the resulting archive will contain a top-level directory by that name). .. note:: The default behavior if the ``--prefix`` option for ``git archive`` is not specified is to not prepend a prefix, so Salt's behavior differs slightly from ``git archive`` in this respect. Use ``prefix=''`` to create an archive with no prefix. .. versionchanged:: 2015.8.0 The behavior of this argument has been changed slightly. As of this version, it is necessary to include the trailing slash when specifying a prefix, if the prefix is intended to create a top-level directory. git_opts Any additional options to add to git command itself (not the ``archive`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-archive(1)`: http://git-scm.com/docs/git-archive CLI Example: .. code-block:: bash salt myminion git.archive /path/to/repo /path/to/archive.tar
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "0", "Returns", "True", "if", "successful", "raises", "an", "error", "if", "not", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L546-L699
train
saltstack/salt
salt/modules/git.py
branch
def branch(cwd, name=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-branch(1)`_ cwd The path to the git checkout name Name of the branch on which to operate. If not specified, the current branch will be assumed. opts Any additional options to add to the command line, in a single string .. note:: To create a branch based on something other than HEAD, pass the name of the revision as ``opts``. If the revision is in the format ``remotename/branch``, then this will also set the remote tracking branch. Additionally, on the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``branch`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-branch(1)`: http://git-scm.com/docs/git-branch CLI Examples: .. code-block:: bash # Set remote tracking branch salt myminion git.branch /path/to/repo mybranch opts='--set-upstream-to origin/mybranch' # Create new branch salt myminion git.branch /path/to/repo mybranch upstream/somebranch # Delete branch salt myminion git.branch /path/to/repo mybranch opts='-d' # Rename branch (2015.8.0 and later) salt myminion git.branch /path/to/repo newbranch opts='-m oldbranch' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('branch') command.extend(_format_opts(opts)) if name is not None: command.append(name) _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) return True
python
def branch(cwd, name=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-branch(1)`_ cwd The path to the git checkout name Name of the branch on which to operate. If not specified, the current branch will be assumed. opts Any additional options to add to the command line, in a single string .. note:: To create a branch based on something other than HEAD, pass the name of the revision as ``opts``. If the revision is in the format ``remotename/branch``, then this will also set the remote tracking branch. Additionally, on the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``branch`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-branch(1)`: http://git-scm.com/docs/git-branch CLI Examples: .. code-block:: bash # Set remote tracking branch salt myminion git.branch /path/to/repo mybranch opts='--set-upstream-to origin/mybranch' # Create new branch salt myminion git.branch /path/to/repo mybranch upstream/somebranch # Delete branch salt myminion git.branch /path/to/repo mybranch opts='-d' # Rename branch (2015.8.0 and later) salt myminion git.branch /path/to/repo newbranch opts='-m oldbranch' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('branch') command.extend(_format_opts(opts)) if name is not None: command.append(name) _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) return True
[ "def", "branch", "(", "cwd", ",", "name", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "...
Interface to `git-branch(1)`_ cwd The path to the git checkout name Name of the branch on which to operate. If not specified, the current branch will be assumed. opts Any additional options to add to the command line, in a single string .. note:: To create a branch based on something other than HEAD, pass the name of the revision as ``opts``. If the revision is in the format ``remotename/branch``, then this will also set the remote tracking branch. Additionally, on the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``branch`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-branch(1)`: http://git-scm.com/docs/git-branch CLI Examples: .. code-block:: bash # Set remote tracking branch salt myminion git.branch /path/to/repo mybranch opts='--set-upstream-to origin/mybranch' # Create new branch salt myminion git.branch /path/to/repo mybranch upstream/somebranch # Delete branch salt myminion git.branch /path/to/repo mybranch opts='-d' # Rename branch (2015.8.0 and later) salt myminion git.branch /path/to/repo newbranch opts='-m oldbranch'
[ "Interface", "to", "git", "-", "branch", "(", "1", ")", "_" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L702-L799
train
saltstack/salt
salt/modules/git.py
checkout
def checkout(cwd, rev=None, force=False, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-checkout(1)`_ cwd The path to the git checkout opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``checkout`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. rev The remote branch or revision to checkout. .. versionchanged:: 2015.8.0 Optional when using ``-b`` or ``-B`` in ``opts``. force : False Force a checkout even if there might be overwritten changes user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-checkout(1)`: http://git-scm.com/docs/git-checkout CLI Examples: .. code-block:: bash # Checking out local local revisions salt myminion git.checkout /path/to/repo somebranch user=jeff salt myminion git.checkout /path/to/repo opts='testbranch -- conf/file1 file2' salt myminion git.checkout /path/to/repo rev=origin/mybranch opts='--track' # Checking out remote revision into new branch salt myminion git.checkout /path/to/repo upstream/master opts='-b newbranch' # Checking out current revision into new branch (2015.8.0 and later) salt myminion git.checkout /path/to/repo opts='-b newbranch' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('checkout') if force: command.append('--force') opts = _format_opts(opts) command.extend(opts) checkout_branch = any(x in opts for x in ('-b', '-B')) if rev is None: if not checkout_branch: raise SaltInvocationError( '\'rev\' argument is required unless -b or -B in opts' ) else: command.append(rev) # Checkout message goes to stderr return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, redirect_stderr=True, output_encoding=output_encoding)['stdout']
python
def checkout(cwd, rev=None, force=False, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-checkout(1)`_ cwd The path to the git checkout opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``checkout`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. rev The remote branch or revision to checkout. .. versionchanged:: 2015.8.0 Optional when using ``-b`` or ``-B`` in ``opts``. force : False Force a checkout even if there might be overwritten changes user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-checkout(1)`: http://git-scm.com/docs/git-checkout CLI Examples: .. code-block:: bash # Checking out local local revisions salt myminion git.checkout /path/to/repo somebranch user=jeff salt myminion git.checkout /path/to/repo opts='testbranch -- conf/file1 file2' salt myminion git.checkout /path/to/repo rev=origin/mybranch opts='--track' # Checking out remote revision into new branch salt myminion git.checkout /path/to/repo upstream/master opts='-b newbranch' # Checking out current revision into new branch (2015.8.0 and later) salt myminion git.checkout /path/to/repo opts='-b newbranch' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('checkout') if force: command.append('--force') opts = _format_opts(opts) command.extend(opts) checkout_branch = any(x in opts for x in ('-b', '-B')) if rev is None: if not checkout_branch: raise SaltInvocationError( '\'rev\' argument is required unless -b or -B in opts' ) else: command.append(rev) # Checkout message goes to stderr return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, redirect_stderr=True, output_encoding=output_encoding)['stdout']
[ "def", "checkout", "(", "cwd", ",", "rev", "=", "None", ",", "force", "=", "False", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding...
Interface to `git-checkout(1)`_ cwd The path to the git checkout opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``checkout`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. rev The remote branch or revision to checkout. .. versionchanged:: 2015.8.0 Optional when using ``-b`` or ``-B`` in ``opts``. force : False Force a checkout even if there might be overwritten changes user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-checkout(1)`: http://git-scm.com/docs/git-checkout CLI Examples: .. code-block:: bash # Checking out local local revisions salt myminion git.checkout /path/to/repo somebranch user=jeff salt myminion git.checkout /path/to/repo opts='testbranch -- conf/file1 file2' salt myminion git.checkout /path/to/repo rev=origin/mybranch opts='--track' # Checking out remote revision into new branch salt myminion git.checkout /path/to/repo upstream/master opts='-b newbranch' # Checking out current revision into new branch (2015.8.0 and later) salt myminion git.checkout /path/to/repo opts='-b newbranch'
[ "Interface", "to", "git", "-", "checkout", "(", "1", ")", "_" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L802-L910
train
saltstack/salt
salt/modules/git.py
clone
def clone(cwd, url=None, # Remove default value once 'repository' arg is removed name=None, opts='', git_opts='', user=None, password=None, identity=None, https_user=None, https_pass=None, ignore_retcode=False, saltenv='base', output_encoding=None): ''' Interface to `git-clone(1)`_ cwd Location of git clone .. versionchanged:: 2015.8.0 If ``name`` is passed, then the clone will be made *within* this directory. url The URL of the repository to be cloned .. versionchanged:: 2015.8.0 Argument renamed from ``repository`` to ``url`` name Optional alternate name for the top-level directory to be created by the clone .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string git_opts Any additional options to add to git command itself (not the ``clone`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. .. versionadded:: 20515.5.0 https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-clone(1)`: http://git-scm.com/docs/git-clone CLI Example: .. code-block:: bash salt myminion git.clone /path/to/repo_parent_dir git://github.com/saltstack/salt.git ''' cwd = _expand_path(cwd, user) if not url: raise SaltInvocationError('Missing \'url\' argument') try: url = salt.utils.url.add_http_basic_auth(url, https_user, https_pass, https_only=True) except ValueError as exc: raise SaltInvocationError(exc.__str__()) command = ['git'] + _format_git_opts(git_opts) command.append('clone') command.extend(_format_opts(opts)) command.extend(['--', url]) if name is not None: command.append(name) if not os.path.exists(cwd): os.makedirs(cwd) clone_cwd = cwd else: command.append(cwd) # Use '/tmp' instead of $HOME (/root for root user) to work around # upstream git bug. See the following comment on the Salt bug tracker # for more info: # https://github.com/saltstack/salt/issues/15519#issuecomment-128531310 # On Windows, just fall back to None (runs git clone command using the # home directory as the cwd). clone_cwd = '/tmp' if not salt.utils.platform.is_windows() else None _git_run(command, cwd=clone_cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, saltenv=saltenv, output_encoding=output_encoding) return True
python
def clone(cwd, url=None, # Remove default value once 'repository' arg is removed name=None, opts='', git_opts='', user=None, password=None, identity=None, https_user=None, https_pass=None, ignore_retcode=False, saltenv='base', output_encoding=None): ''' Interface to `git-clone(1)`_ cwd Location of git clone .. versionchanged:: 2015.8.0 If ``name`` is passed, then the clone will be made *within* this directory. url The URL of the repository to be cloned .. versionchanged:: 2015.8.0 Argument renamed from ``repository`` to ``url`` name Optional alternate name for the top-level directory to be created by the clone .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string git_opts Any additional options to add to git command itself (not the ``clone`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. .. versionadded:: 20515.5.0 https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-clone(1)`: http://git-scm.com/docs/git-clone CLI Example: .. code-block:: bash salt myminion git.clone /path/to/repo_parent_dir git://github.com/saltstack/salt.git ''' cwd = _expand_path(cwd, user) if not url: raise SaltInvocationError('Missing \'url\' argument') try: url = salt.utils.url.add_http_basic_auth(url, https_user, https_pass, https_only=True) except ValueError as exc: raise SaltInvocationError(exc.__str__()) command = ['git'] + _format_git_opts(git_opts) command.append('clone') command.extend(_format_opts(opts)) command.extend(['--', url]) if name is not None: command.append(name) if not os.path.exists(cwd): os.makedirs(cwd) clone_cwd = cwd else: command.append(cwd) # Use '/tmp' instead of $HOME (/root for root user) to work around # upstream git bug. See the following comment on the Salt bug tracker # for more info: # https://github.com/saltstack/salt/issues/15519#issuecomment-128531310 # On Windows, just fall back to None (runs git clone command using the # home directory as the cwd). clone_cwd = '/tmp' if not salt.utils.platform.is_windows() else None _git_run(command, cwd=clone_cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, saltenv=saltenv, output_encoding=output_encoding) return True
[ "def", "clone", "(", "cwd", ",", "url", "=", "None", ",", "# Remove default value once 'repository' arg is removed", "name", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "iden...
Interface to `git-clone(1)`_ cwd Location of git clone .. versionchanged:: 2015.8.0 If ``name`` is passed, then the clone will be made *within* this directory. url The URL of the repository to be cloned .. versionchanged:: 2015.8.0 Argument renamed from ``repository`` to ``url`` name Optional alternate name for the top-level directory to be created by the clone .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string git_opts Any additional options to add to git command itself (not the ``clone`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. .. versionadded:: 20515.5.0 https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-clone(1)`: http://git-scm.com/docs/git-clone CLI Example: .. code-block:: bash salt myminion git.clone /path/to/repo_parent_dir git://github.com/saltstack/salt.git
[ "Interface", "to", "git", "-", "clone", "(", "1", ")", "_" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L913-L1074
train
saltstack/salt
salt/modules/git.py
commit
def commit(cwd, message, opts='', git_opts='', user=None, password=None, filename=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-commit(1)`_ cwd The path to the git checkout message Commit message opts Any additional options to add to the command line, in a single string. These opts will be added to the end of the git command being run. .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. The ``-m`` option should not be passed here, as the commit message will be defined by the ``message`` argument. git_opts Any additional options to add to git command itself (not the ``commit`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 filename The location of the file/directory to commit, relative to ``cwd``. This argument is optional, and can be used to commit a file without first staging it. .. note:: This argument only works on files which are already tracked by the git repository. .. versionadded:: 2015.8.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-commit(1)`: http://git-scm.com/docs/git-commit CLI Examples: .. code-block:: bash salt myminion git.commit /path/to/repo 'The commit message' salt myminion git.commit /path/to/repo 'The commit message' filename=foo/bar.py ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.extend(['commit', '-m', message]) command.extend(_format_opts(opts)) if filename: # Add the '--' to terminate CLI args, but only if it wasn't already # passed in opts string. command.extend(['--', filename]) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def commit(cwd, message, opts='', git_opts='', user=None, password=None, filename=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-commit(1)`_ cwd The path to the git checkout message Commit message opts Any additional options to add to the command line, in a single string. These opts will be added to the end of the git command being run. .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. The ``-m`` option should not be passed here, as the commit message will be defined by the ``message`` argument. git_opts Any additional options to add to git command itself (not the ``commit`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 filename The location of the file/directory to commit, relative to ``cwd``. This argument is optional, and can be used to commit a file without first staging it. .. note:: This argument only works on files which are already tracked by the git repository. .. versionadded:: 2015.8.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-commit(1)`: http://git-scm.com/docs/git-commit CLI Examples: .. code-block:: bash salt myminion git.commit /path/to/repo 'The commit message' salt myminion git.commit /path/to/repo 'The commit message' filename=foo/bar.py ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.extend(['commit', '-m', message]) command.extend(_format_opts(opts)) if filename: # Add the '--' to terminate CLI args, but only if it wasn't already # passed in opts string. command.extend(['--', filename]) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "commit", "(", "cwd", ",", "message", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "filename", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "...
Interface to `git-commit(1)`_ cwd The path to the git checkout message Commit message opts Any additional options to add to the command line, in a single string. These opts will be added to the end of the git command being run. .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. The ``-m`` option should not be passed here, as the commit message will be defined by the ``message`` argument. git_opts Any additional options to add to git command itself (not the ``commit`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 filename The location of the file/directory to commit, relative to ``cwd``. This argument is optional, and can be used to commit a file without first staging it. .. note:: This argument only works on files which are already tracked by the git repository. .. versionadded:: 2015.8.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-commit(1)`: http://git-scm.com/docs/git-commit CLI Examples: .. code-block:: bash salt myminion git.commit /path/to/repo 'The commit message' salt myminion git.commit /path/to/repo 'The commit message' filename=foo/bar.py
[ "Interface", "to", "git", "-", "commit", "(", "1", ")", "_" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L1077-L1178
train
saltstack/salt
salt/modules/git.py
config_get
def config_get(key, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Get the value of a key in the git configuration file key The name of the configuration key to get .. versionchanged:: 2015.8.0 Argument renamed from ``setting_name`` to ``key`` cwd The path to the git checkout .. versionchanged:: 2015.8.0 Now optional if ``global`` is set to ``True`` global : False If ``True``, query the global git configuration. Otherwise, only the local git configuration will be queried. .. versionadded:: 2015.8.0 all : False If ``True``, return a list of all values set for ``key``. If the key does not exist, ``None`` will be returned. .. versionadded:: 2015.8.0 user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.config_get user.name cwd=/path/to/repo salt myminion git.config_get user.email global=True salt myminion git.config_get core.gitproxy cwd=/path/to/repo all=True ''' # Sanitize kwargs and make sure that no invalid ones were passed. This # allows us to accept 'all' as an argument to this function without # shadowing all(), while also not allowing unwanted arguments to be passed. all_ = kwargs.pop('all', False) result = _config_getter('--get-all', key, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding, **kwargs) # git config --get exits with retcode of 1 when key does not exist if result['retcode'] == 1: return None ret = result['stdout'].splitlines() if all_: return ret else: try: return ret[-1] except IndexError: # Should never happen but I'm paranoid and don't like tracebacks return ''
python
def config_get(key, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Get the value of a key in the git configuration file key The name of the configuration key to get .. versionchanged:: 2015.8.0 Argument renamed from ``setting_name`` to ``key`` cwd The path to the git checkout .. versionchanged:: 2015.8.0 Now optional if ``global`` is set to ``True`` global : False If ``True``, query the global git configuration. Otherwise, only the local git configuration will be queried. .. versionadded:: 2015.8.0 all : False If ``True``, return a list of all values set for ``key``. If the key does not exist, ``None`` will be returned. .. versionadded:: 2015.8.0 user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.config_get user.name cwd=/path/to/repo salt myminion git.config_get user.email global=True salt myminion git.config_get core.gitproxy cwd=/path/to/repo all=True ''' # Sanitize kwargs and make sure that no invalid ones were passed. This # allows us to accept 'all' as an argument to this function without # shadowing all(), while also not allowing unwanted arguments to be passed. all_ = kwargs.pop('all', False) result = _config_getter('--get-all', key, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding, **kwargs) # git config --get exits with retcode of 1 when key does not exist if result['retcode'] == 1: return None ret = result['stdout'].splitlines() if all_: return ret else: try: return ret[-1] except IndexError: # Should never happen but I'm paranoid and don't like tracebacks return ''
[ "def", "config_get", "(", "key", ",", "cwd", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Sanitize kwargs and make sure ...
Get the value of a key in the git configuration file key The name of the configuration key to get .. versionchanged:: 2015.8.0 Argument renamed from ``setting_name`` to ``key`` cwd The path to the git checkout .. versionchanged:: 2015.8.0 Now optional if ``global`` is set to ``True`` global : False If ``True``, query the global git configuration. Otherwise, only the local git configuration will be queried. .. versionadded:: 2015.8.0 all : False If ``True``, return a list of all values set for ``key``. If the key does not exist, ``None`` will be returned. .. versionadded:: 2015.8.0 user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.config_get user.name cwd=/path/to/repo salt myminion git.config_get user.email global=True salt myminion git.config_get core.gitproxy cwd=/path/to/repo all=True
[ "Get", "the", "value", "of", "a", "key", "in", "the", "git", "configuration", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L1181-L1276
train
saltstack/salt
salt/modules/git.py
config_get_regexp
def config_get_regexp(key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): r''' .. versionadded:: 2015.8.0 Get the value of a key or keys in the git configuration file using regexes for more flexible matching. The return data is a dictionary mapping keys to lists of values matching the ``value_regex``. If no values match, an empty dictionary will be returned. key Regex on which key names will be matched value_regex If specified, return all values matching this regex. The return data will be a dictionary mapping keys to lists of values matching the regex. .. important:: Only values matching the ``value_regex`` will be part of the return data. So, if ``key`` matches a multivar, then it is possible that not all of the values will be returned. To get all values set for a multivar, simply omit the ``value_regex`` argument. cwd The path to the git checkout global : False If ``True``, query the global git configuration. Otherwise, only the local git configuration will be queried. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash # Matches any values for key 'foo.bar' salt myminion git.config_get_regexp /path/to/repo foo.bar # Matches any value starting with 'baz' set for key 'foo.bar' salt myminion git.config_get_regexp /path/to/repo foo.bar 'baz.*' # Matches any key starting with 'user.' salt myminion git.config_get_regexp '^user\.' global=True ''' result = _config_getter('--get-regexp', key, value_regex=value_regex, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding, **kwargs) # git config --get exits with retcode of 1 when key does not exist ret = {} if result['retcode'] == 1: return ret for line in result['stdout'].splitlines(): try: param, value = line.split(None, 1) except ValueError: continue ret.setdefault(param, []).append(value) return ret
python
def config_get_regexp(key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): r''' .. versionadded:: 2015.8.0 Get the value of a key or keys in the git configuration file using regexes for more flexible matching. The return data is a dictionary mapping keys to lists of values matching the ``value_regex``. If no values match, an empty dictionary will be returned. key Regex on which key names will be matched value_regex If specified, return all values matching this regex. The return data will be a dictionary mapping keys to lists of values matching the regex. .. important:: Only values matching the ``value_regex`` will be part of the return data. So, if ``key`` matches a multivar, then it is possible that not all of the values will be returned. To get all values set for a multivar, simply omit the ``value_regex`` argument. cwd The path to the git checkout global : False If ``True``, query the global git configuration. Otherwise, only the local git configuration will be queried. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash # Matches any values for key 'foo.bar' salt myminion git.config_get_regexp /path/to/repo foo.bar # Matches any value starting with 'baz' set for key 'foo.bar' salt myminion git.config_get_regexp /path/to/repo foo.bar 'baz.*' # Matches any key starting with 'user.' salt myminion git.config_get_regexp '^user\.' global=True ''' result = _config_getter('--get-regexp', key, value_regex=value_regex, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding, **kwargs) # git config --get exits with retcode of 1 when key does not exist ret = {} if result['retcode'] == 1: return ret for line in result['stdout'].splitlines(): try: param, value = line.split(None, 1) except ValueError: continue ret.setdefault(param, []).append(value) return ret
[ "def", "config_get_regexp", "(", "key", ",", "value_regex", "=", "None", ",", "cwd", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ",", "*", "*", "kwargs", ...
r''' .. versionadded:: 2015.8.0 Get the value of a key or keys in the git configuration file using regexes for more flexible matching. The return data is a dictionary mapping keys to lists of values matching the ``value_regex``. If no values match, an empty dictionary will be returned. key Regex on which key names will be matched value_regex If specified, return all values matching this regex. The return data will be a dictionary mapping keys to lists of values matching the regex. .. important:: Only values matching the ``value_regex`` will be part of the return data. So, if ``key`` matches a multivar, then it is possible that not all of the values will be returned. To get all values set for a multivar, simply omit the ``value_regex`` argument. cwd The path to the git checkout global : False If ``True``, query the global git configuration. Otherwise, only the local git configuration will be queried. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash # Matches any values for key 'foo.bar' salt myminion git.config_get_regexp /path/to/repo foo.bar # Matches any value starting with 'baz' set for key 'foo.bar' salt myminion git.config_get_regexp /path/to/repo foo.bar 'baz.*' # Matches any key starting with 'user.' salt myminion git.config_get_regexp '^user\.' global=True
[ "r", "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L1279-L1373
train
saltstack/salt
salt/modules/git.py
config_set
def config_set(key, value=None, multivar=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionchanged:: 2015.8.0 Return the value(s) of the key being set Set a key in the git configuration file cwd The path to the git checkout. Must be an absolute path, or the word ``global`` to indicate that a global key should be set. .. versionchanged:: 2014.7.0 Made ``cwd`` argument optional if ``is_global=True`` key The name of the configuration key to set .. versionchanged:: 2015.8.0 Argument renamed from ``setting_name`` to ``key`` value The value to set for the specified key. Incompatible with the ``multivar`` argument. .. versionchanged:: 2015.8.0 Argument renamed from ``setting_value`` to ``value`` add : False Add a value to a key, creating/updating a multivar .. versionadded:: 2015.8.0 multivar Set a multivar all at once. Values can be comma-separated or passed as a Python list. Incompatible with the ``value`` argument. .. versionadded:: 2015.8.0 user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 global : False If ``True``, set a global variable output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.config_set user.email me@example.com cwd=/path/to/repo salt myminion git.config_set user.email foo@bar.com global=True ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) add_ = kwargs.pop('add', False) global_ = kwargs.pop('global', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if cwd is None: if not global_: raise SaltInvocationError( '\'cwd\' argument required unless global=True' ) else: cwd = _expand_path(cwd, user) if all(x is not None for x in (value, multivar)): raise SaltInvocationError( 'Only one of \'value\' and \'multivar\' is permitted' ) if multivar is not None: if not isinstance(multivar, list): try: multivar = multivar.split(',') except AttributeError: multivar = six.text_type(multivar).split(',') else: new_multivar = [] for item in salt.utils.data.decode(multivar): if isinstance(item, six.string_types): new_multivar.append(item) else: new_multivar.append(six.text_type(item)) multivar = new_multivar command_prefix = ['git', 'config'] if global_: command_prefix.append('--global') if value is not None: command = copy.copy(command_prefix) if add_: command.append('--add') else: command.append('--replace-all') command.extend([key, value]) _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) else: for idx, target in enumerate(multivar): command = copy.copy(command_prefix) if idx == 0: command.append('--replace-all') else: command.append('--add') command.extend([key, target]) _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) return config_get(key, user=user, password=password, cwd=cwd, ignore_retcode=ignore_retcode, output_encoding=output_encoding, **{'all': True, 'global': global_})
python
def config_set(key, value=None, multivar=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionchanged:: 2015.8.0 Return the value(s) of the key being set Set a key in the git configuration file cwd The path to the git checkout. Must be an absolute path, or the word ``global`` to indicate that a global key should be set. .. versionchanged:: 2014.7.0 Made ``cwd`` argument optional if ``is_global=True`` key The name of the configuration key to set .. versionchanged:: 2015.8.0 Argument renamed from ``setting_name`` to ``key`` value The value to set for the specified key. Incompatible with the ``multivar`` argument. .. versionchanged:: 2015.8.0 Argument renamed from ``setting_value`` to ``value`` add : False Add a value to a key, creating/updating a multivar .. versionadded:: 2015.8.0 multivar Set a multivar all at once. Values can be comma-separated or passed as a Python list. Incompatible with the ``value`` argument. .. versionadded:: 2015.8.0 user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 global : False If ``True``, set a global variable output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.config_set user.email me@example.com cwd=/path/to/repo salt myminion git.config_set user.email foo@bar.com global=True ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) add_ = kwargs.pop('add', False) global_ = kwargs.pop('global', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if cwd is None: if not global_: raise SaltInvocationError( '\'cwd\' argument required unless global=True' ) else: cwd = _expand_path(cwd, user) if all(x is not None for x in (value, multivar)): raise SaltInvocationError( 'Only one of \'value\' and \'multivar\' is permitted' ) if multivar is not None: if not isinstance(multivar, list): try: multivar = multivar.split(',') except AttributeError: multivar = six.text_type(multivar).split(',') else: new_multivar = [] for item in salt.utils.data.decode(multivar): if isinstance(item, six.string_types): new_multivar.append(item) else: new_multivar.append(six.text_type(item)) multivar = new_multivar command_prefix = ['git', 'config'] if global_: command_prefix.append('--global') if value is not None: command = copy.copy(command_prefix) if add_: command.append('--add') else: command.append('--replace-all') command.extend([key, value]) _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) else: for idx, target in enumerate(multivar): command = copy.copy(command_prefix) if idx == 0: command.append('--replace-all') else: command.append('--add') command.extend([key, target]) _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) return config_get(key, user=user, password=password, cwd=cwd, ignore_retcode=ignore_retcode, output_encoding=output_encoding, **{'all': True, 'global': global_})
[ "def", "config_set", "(", "key", ",", "value", "=", "None", ",", "multivar", "=", "None", ",", "cwd", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ",", ...
.. versionchanged:: 2015.8.0 Return the value(s) of the key being set Set a key in the git configuration file cwd The path to the git checkout. Must be an absolute path, or the word ``global`` to indicate that a global key should be set. .. versionchanged:: 2014.7.0 Made ``cwd`` argument optional if ``is_global=True`` key The name of the configuration key to set .. versionchanged:: 2015.8.0 Argument renamed from ``setting_name`` to ``key`` value The value to set for the specified key. Incompatible with the ``multivar`` argument. .. versionchanged:: 2015.8.0 Argument renamed from ``setting_value`` to ``value`` add : False Add a value to a key, creating/updating a multivar .. versionadded:: 2015.8.0 multivar Set a multivar all at once. Values can be comma-separated or passed as a Python list. Incompatible with the ``value`` argument. .. versionadded:: 2015.8.0 user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 global : False If ``True``, set a global variable output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.config_set user.email me@example.com cwd=/path/to/repo salt myminion git.config_set user.email foo@bar.com global=True
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "0", "Return", "the", "value", "(", "s", ")", "of", "the", "key", "being", "set" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L1379-L1534
train
saltstack/salt
salt/modules/git.py
config_unset
def config_unset(key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionadded:: 2015.8.0 Unset a key in the git configuration file cwd The path to the git checkout. Must be an absolute path, or the word ``global`` to indicate that a global key should be unset. key The name of the configuration key to unset value_regex Regular expression that matches exactly one key, used to delete a single value from a multivar. Ignored if ``all`` is set to ``True``. all : False If ``True`` unset all values for a multivar. If ``False``, and ``key`` is a multivar, an error will be raised. global : False If ``True``, unset set a global variable. Otherwise, a local variable will be unset. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.config_unset /path/to/repo foo.bar salt myminion git.config_unset /path/to/repo foo.bar all=True ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) all_ = kwargs.pop('all', False) global_ = kwargs.pop('global', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if cwd is None: if not global_: raise SaltInvocationError( '\'cwd\' argument required unless global=True' ) else: cwd = _expand_path(cwd, user) command = ['git', 'config'] if all_: command.append('--unset-all') else: command.append('--unset') command.extend(_which_git_config(global_, cwd, user, password, output_encoding=output_encoding)) command.append(key) if value_regex is not None: command.append(value_regex) ret = _git_run(command, cwd=cwd if cwd != 'global' else None, user=user, password=password, ignore_retcode=ignore_retcode, failhard=False, output_encoding=output_encoding) retcode = ret['retcode'] if retcode == 0: return True elif retcode == 1: raise CommandExecutionError('Section or key is invalid') elif retcode == 5: if config_get(cwd, key, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) is None: raise CommandExecutionError( 'Key \'{0}\' does not exist'.format(key) ) else: msg = 'Multiple values exist for key \'{0}\''.format(key) if value_regex is not None: msg += ' and value_regex matches multiple values' raise CommandExecutionError(msg) elif retcode == 6: raise CommandExecutionError('The value_regex is invalid') else: msg = ( 'Failed to unset key \'{0}\', git config returned exit code {1}' .format(key, retcode) ) if ret['stderr']: msg += '; ' + ret['stderr'] raise CommandExecutionError(msg)
python
def config_unset(key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionadded:: 2015.8.0 Unset a key in the git configuration file cwd The path to the git checkout. Must be an absolute path, or the word ``global`` to indicate that a global key should be unset. key The name of the configuration key to unset value_regex Regular expression that matches exactly one key, used to delete a single value from a multivar. Ignored if ``all`` is set to ``True``. all : False If ``True`` unset all values for a multivar. If ``False``, and ``key`` is a multivar, an error will be raised. global : False If ``True``, unset set a global variable. Otherwise, a local variable will be unset. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.config_unset /path/to/repo foo.bar salt myminion git.config_unset /path/to/repo foo.bar all=True ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) all_ = kwargs.pop('all', False) global_ = kwargs.pop('global', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if cwd is None: if not global_: raise SaltInvocationError( '\'cwd\' argument required unless global=True' ) else: cwd = _expand_path(cwd, user) command = ['git', 'config'] if all_: command.append('--unset-all') else: command.append('--unset') command.extend(_which_git_config(global_, cwd, user, password, output_encoding=output_encoding)) command.append(key) if value_regex is not None: command.append(value_regex) ret = _git_run(command, cwd=cwd if cwd != 'global' else None, user=user, password=password, ignore_retcode=ignore_retcode, failhard=False, output_encoding=output_encoding) retcode = ret['retcode'] if retcode == 0: return True elif retcode == 1: raise CommandExecutionError('Section or key is invalid') elif retcode == 5: if config_get(cwd, key, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) is None: raise CommandExecutionError( 'Key \'{0}\' does not exist'.format(key) ) else: msg = 'Multiple values exist for key \'{0}\''.format(key) if value_regex is not None: msg += ' and value_regex matches multiple values' raise CommandExecutionError(msg) elif retcode == 6: raise CommandExecutionError('The value_regex is invalid') else: msg = ( 'Failed to unset key \'{0}\', git config returned exit code {1}' .format(key, retcode) ) if ret['stderr']: msg += '; ' + ret['stderr'] raise CommandExecutionError(msg)
[ "def", "config_unset", "(", "key", ",", "value_regex", "=", "None", ",", "cwd", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ",", "*", "*", "kwargs", ")",...
.. versionadded:: 2015.8.0 Unset a key in the git configuration file cwd The path to the git checkout. Must be an absolute path, or the word ``global`` to indicate that a global key should be unset. key The name of the configuration key to unset value_regex Regular expression that matches exactly one key, used to delete a single value from a multivar. Ignored if ``all`` is set to ``True``. all : False If ``True`` unset all values for a multivar. If ``False``, and ``key`` is a multivar, an error will be raised. global : False If ``True``, unset set a global variable. Otherwise, a local variable will be unset. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.config_unset /path/to/repo foo.bar salt myminion git.config_unset /path/to/repo foo.bar all=True
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L1537-L1663
train
saltstack/salt
salt/modules/git.py
current_branch
def current_branch(cwd, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Returns the current branch name of a local checkout. If HEAD is detached, return the SHA1 of the revision which is currently checked out. cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.current_branch /path/to/repo ''' cwd = _expand_path(cwd, user) command = ['git', 'rev-parse', '--abbrev-ref', 'HEAD'] return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def current_branch(cwd, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Returns the current branch name of a local checkout. If HEAD is detached, return the SHA1 of the revision which is currently checked out. cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.current_branch /path/to/repo ''' cwd = _expand_path(cwd, user) command = ['git', 'rev-parse', '--abbrev-ref', 'HEAD'] return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "current_branch", "(", "cwd", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", "user", ")", "command", "=", "...
Returns the current branch name of a local checkout. If HEAD is detached, return the SHA1 of the revision which is currently checked out. cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.current_branch /path/to/repo
[ "Returns", "the", "current", "branch", "name", "of", "a", "local", "checkout", ".", "If", "HEAD", "is", "detached", "return", "the", "SHA1", "of", "the", "revision", "which", "is", "currently", "checked", "out", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L1666-L1719
train
saltstack/salt
salt/modules/git.py
describe
def describe(cwd, rev='HEAD', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Returns the `git-describe(1)`_ string (or the SHA1 hash if there are no tags) for the given revision. cwd The path to the git checkout rev : HEAD The revision to describe user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-describe(1)`: http://git-scm.com/docs/git-describe CLI Examples: .. code-block:: bash salt myminion git.describe /path/to/repo salt myminion git.describe /path/to/repo develop ''' cwd = _expand_path(cwd, user) command = ['git', 'describe'] if _LooseVersion(version(versioninfo=False)) >= _LooseVersion('1.5.6'): command.append('--always') command.append(rev) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def describe(cwd, rev='HEAD', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Returns the `git-describe(1)`_ string (or the SHA1 hash if there are no tags) for the given revision. cwd The path to the git checkout rev : HEAD The revision to describe user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-describe(1)`: http://git-scm.com/docs/git-describe CLI Examples: .. code-block:: bash salt myminion git.describe /path/to/repo salt myminion git.describe /path/to/repo develop ''' cwd = _expand_path(cwd, user) command = ['git', 'describe'] if _LooseVersion(version(versioninfo=False)) >= _LooseVersion('1.5.6'): command.append('--always') command.append(rev) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "describe", "(", "cwd", ",", "rev", "=", "'HEAD'", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", "user", ...
Returns the `git-describe(1)`_ string (or the SHA1 hash if there are no tags) for the given revision. cwd The path to the git checkout rev : HEAD The revision to describe user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-describe(1)`: http://git-scm.com/docs/git-describe CLI Examples: .. code-block:: bash salt myminion git.describe /path/to/repo salt myminion git.describe /path/to/repo develop
[ "Returns", "the", "git", "-", "describe", "(", "1", ")", "_", "string", "(", "or", "the", "SHA1", "hash", "if", "there", "are", "no", "tags", ")", "for", "the", "given", "revision", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L1722-L1785
train
saltstack/salt
salt/modules/git.py
diff
def diff(cwd, item1=None, item2=None, opts='', git_opts='', user=None, password=None, no_index=False, cached=False, paths=None, output_encoding=None): ''' .. versionadded:: 2015.8.12,2016.3.3,2016.11.0 Interface to `git-diff(1)`_ cwd The path to the git checkout item1 and item2 Revision(s) to pass to the ``git diff`` command. One or both of these arguments may be ignored if some of the options below are set to ``True``. When ``cached`` is ``False``, and no revisions are passed to this function, then the current working tree will be compared against the index (i.e. unstaged changes). When two revisions are passed, they will be compared to each other. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``diff`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 no_index : False When it is necessary to diff two files in the same repo against each other, and not diff two different revisions, set this option to ``True``. If this is left ``False`` in these instances, then a normal ``git diff`` will be performed against the index (i.e. unstaged changes), and files in the ``paths`` option will be used to narrow down the diff output. .. note:: Requires Git 1.5.1 or newer. Additionally, when set to ``True``, ``item1`` and ``item2`` will be ignored. cached : False If ``True``, compare staged changes to ``item1`` (if specified), otherwise compare them to the most recent commit. .. note:: ``item2`` is ignored if this option is is set to ``True``. paths File paths to pass to the ``git diff`` command. Can be passed as a comma-separated list or a Python list. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-diff(1)`: http://git-scm.com/docs/git-diff CLI Example: .. code-block:: bash # Perform diff against the index (staging area for next commit) salt myminion git.diff /path/to/repo # Compare staged changes to the most recent commit salt myminion git.diff /path/to/repo cached=True # Compare staged changes to a specific revision salt myminion git.diff /path/to/repo mybranch cached=True # Perform diff against the most recent commit (includes staged changes) salt myminion git.diff /path/to/repo HEAD # Diff two commits salt myminion git.diff /path/to/repo abcdef1 aabbccd # Diff two commits, only showing differences in the specified paths salt myminion git.diff /path/to/repo abcdef1 aabbccd paths=path/to/file1,path/to/file2 # Diff two files with one being outside the working tree salt myminion git.diff /path/to/repo no_index=True paths=path/to/file1,/absolute/path/to/file2 ''' if no_index and cached: raise CommandExecutionError( 'The \'no_index\' and \'cached\' options cannot be used together' ) command = ['git'] + _format_git_opts(git_opts) command.append('diff') command.extend(_format_opts(opts)) if paths is not None and not isinstance(paths, (list, tuple)): try: paths = paths.split(',') except AttributeError: paths = six.text_type(paths).split(',') ignore_retcode = False failhard = True if no_index: if _LooseVersion(version(versioninfo=False)) < _LooseVersion('1.5.1'): raise CommandExecutionError( 'The \'no_index\' option is only supported in Git 1.5.1 and ' 'newer' ) ignore_retcode = True failhard = False command.append('--no-index') for value in [x for x in (item1, item2) if x]: log.warning( 'Revision \'%s\' ignored in git diff, as revisions cannot be ' 'used when no_index=True', value ) elif cached: command.append('--cached') if item1: command.append(item1) if item2: log.warning( 'Second revision \'%s\' ignored in git diff, at most one ' 'revision is considered when cached=True', item2 ) else: for value in [x for x in (item1, item2) if x]: command.append(value) if paths: command.append('--') command.extend(paths) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, failhard=failhard, redirect_stderr=True, output_encoding=output_encoding)['stdout']
python
def diff(cwd, item1=None, item2=None, opts='', git_opts='', user=None, password=None, no_index=False, cached=False, paths=None, output_encoding=None): ''' .. versionadded:: 2015.8.12,2016.3.3,2016.11.0 Interface to `git-diff(1)`_ cwd The path to the git checkout item1 and item2 Revision(s) to pass to the ``git diff`` command. One or both of these arguments may be ignored if some of the options below are set to ``True``. When ``cached`` is ``False``, and no revisions are passed to this function, then the current working tree will be compared against the index (i.e. unstaged changes). When two revisions are passed, they will be compared to each other. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``diff`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 no_index : False When it is necessary to diff two files in the same repo against each other, and not diff two different revisions, set this option to ``True``. If this is left ``False`` in these instances, then a normal ``git diff`` will be performed against the index (i.e. unstaged changes), and files in the ``paths`` option will be used to narrow down the diff output. .. note:: Requires Git 1.5.1 or newer. Additionally, when set to ``True``, ``item1`` and ``item2`` will be ignored. cached : False If ``True``, compare staged changes to ``item1`` (if specified), otherwise compare them to the most recent commit. .. note:: ``item2`` is ignored if this option is is set to ``True``. paths File paths to pass to the ``git diff`` command. Can be passed as a comma-separated list or a Python list. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-diff(1)`: http://git-scm.com/docs/git-diff CLI Example: .. code-block:: bash # Perform diff against the index (staging area for next commit) salt myminion git.diff /path/to/repo # Compare staged changes to the most recent commit salt myminion git.diff /path/to/repo cached=True # Compare staged changes to a specific revision salt myminion git.diff /path/to/repo mybranch cached=True # Perform diff against the most recent commit (includes staged changes) salt myminion git.diff /path/to/repo HEAD # Diff two commits salt myminion git.diff /path/to/repo abcdef1 aabbccd # Diff two commits, only showing differences in the specified paths salt myminion git.diff /path/to/repo abcdef1 aabbccd paths=path/to/file1,path/to/file2 # Diff two files with one being outside the working tree salt myminion git.diff /path/to/repo no_index=True paths=path/to/file1,/absolute/path/to/file2 ''' if no_index and cached: raise CommandExecutionError( 'The \'no_index\' and \'cached\' options cannot be used together' ) command = ['git'] + _format_git_opts(git_opts) command.append('diff') command.extend(_format_opts(opts)) if paths is not None and not isinstance(paths, (list, tuple)): try: paths = paths.split(',') except AttributeError: paths = six.text_type(paths).split(',') ignore_retcode = False failhard = True if no_index: if _LooseVersion(version(versioninfo=False)) < _LooseVersion('1.5.1'): raise CommandExecutionError( 'The \'no_index\' option is only supported in Git 1.5.1 and ' 'newer' ) ignore_retcode = True failhard = False command.append('--no-index') for value in [x for x in (item1, item2) if x]: log.warning( 'Revision \'%s\' ignored in git diff, as revisions cannot be ' 'used when no_index=True', value ) elif cached: command.append('--cached') if item1: command.append(item1) if item2: log.warning( 'Second revision \'%s\' ignored in git diff, at most one ' 'revision is considered when cached=True', item2 ) else: for value in [x for x in (item1, item2) if x]: command.append(value) if paths: command.append('--') command.extend(paths) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, failhard=failhard, redirect_stderr=True, output_encoding=output_encoding)['stdout']
[ "def", "diff", "(", "cwd", ",", "item1", "=", "None", ",", "item2", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "no_index", "=", "False", ",", "cached", "=", "False...
.. versionadded:: 2015.8.12,2016.3.3,2016.11.0 Interface to `git-diff(1)`_ cwd The path to the git checkout item1 and item2 Revision(s) to pass to the ``git diff`` command. One or both of these arguments may be ignored if some of the options below are set to ``True``. When ``cached`` is ``False``, and no revisions are passed to this function, then the current working tree will be compared against the index (i.e. unstaged changes). When two revisions are passed, they will be compared to each other. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``diff`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 no_index : False When it is necessary to diff two files in the same repo against each other, and not diff two different revisions, set this option to ``True``. If this is left ``False`` in these instances, then a normal ``git diff`` will be performed against the index (i.e. unstaged changes), and files in the ``paths`` option will be used to narrow down the diff output. .. note:: Requires Git 1.5.1 or newer. Additionally, when set to ``True``, ``item1`` and ``item2`` will be ignored. cached : False If ``True``, compare staged changes to ``item1`` (if specified), otherwise compare them to the most recent commit. .. note:: ``item2`` is ignored if this option is is set to ``True``. paths File paths to pass to the ``git diff`` command. Can be passed as a comma-separated list or a Python list. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-diff(1)`: http://git-scm.com/docs/git-diff CLI Example: .. code-block:: bash # Perform diff against the index (staging area for next commit) salt myminion git.diff /path/to/repo # Compare staged changes to the most recent commit salt myminion git.diff /path/to/repo cached=True # Compare staged changes to a specific revision salt myminion git.diff /path/to/repo mybranch cached=True # Perform diff against the most recent commit (includes staged changes) salt myminion git.diff /path/to/repo HEAD # Diff two commits salt myminion git.diff /path/to/repo abcdef1 aabbccd # Diff two commits, only showing differences in the specified paths salt myminion git.diff /path/to/repo abcdef1 aabbccd paths=path/to/file1,path/to/file2 # Diff two files with one being outside the working tree salt myminion git.diff /path/to/repo no_index=True paths=path/to/file1,/absolute/path/to/file2
[ "..", "versionadded", "::", "2015", ".", "8", ".", "12", "2016", ".", "3", ".", "3", "2016", ".", "11", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L1788-L1957
train
saltstack/salt
salt/modules/git.py
discard_local_changes
def discard_local_changes(cwd, path='.', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2019.2.0 Runs a ``git checkout -- <path>`` from the directory specified by ``cwd``. cwd The path to the git checkout path path relative to cwd (defaults to ``.``) user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. CLI Example: .. code-block:: bash salt myminion git.discard_local_changes /path/to/repo salt myminion git.discard_local_changes /path/to/repo path=foo ''' cwd = _expand_path(cwd, user) command = ['git', 'checkout', '--', path] # Checkout message goes to stderr return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, redirect_stderr=True, output_encoding=output_encoding)['stdout']
python
def discard_local_changes(cwd, path='.', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2019.2.0 Runs a ``git checkout -- <path>`` from the directory specified by ``cwd``. cwd The path to the git checkout path path relative to cwd (defaults to ``.``) user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. CLI Example: .. code-block:: bash salt myminion git.discard_local_changes /path/to/repo salt myminion git.discard_local_changes /path/to/repo path=foo ''' cwd = _expand_path(cwd, user) command = ['git', 'checkout', '--', path] # Checkout message goes to stderr return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, redirect_stderr=True, output_encoding=output_encoding)['stdout']
[ "def", "discard_local_changes", "(", "cwd", ",", "path", "=", "'.'", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", ...
.. versionadded:: 2019.2.0 Runs a ``git checkout -- <path>`` from the directory specified by ``cwd``. cwd The path to the git checkout path path relative to cwd (defaults to ``.``) user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. CLI Example: .. code-block:: bash salt myminion git.discard_local_changes /path/to/repo salt myminion git.discard_local_changes /path/to/repo path=foo
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L1960-L2015
train
saltstack/salt
salt/modules/git.py
fetch
def fetch(cwd, remote=None, force=False, refspecs=None, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, saltenv='base', output_encoding=None): ''' .. versionchanged:: 2015.8.2 Return data is now a dictionary containing information on branches and tags that were added/updated Interface to `git-fetch(1)`_ cwd The path to the git checkout remote Optional remote name to fetch. If not passed, then git will use its default behavior (as detailed in `git-fetch(1)`_). .. versionadded:: 2015.8.0 force Force the fetch even when it is not a fast-forward. .. versionadded:: 2015.8.0 refspecs Override the refspec(s) configured for the remote with this argument. Multiple refspecs can be passed, comma-separated. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``fetch`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-fetch(1)`: http://git-scm.com/docs/git-fetch CLI Example: .. code-block:: bash salt myminion git.fetch /path/to/repo upstream salt myminion git.fetch /path/to/repo identity=/root/.ssh/id_rsa ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('fetch') if force: command.append('--force') command.extend( [x for x in _format_opts(opts) if x not in ('-f', '--force')] ) if remote: command.append(remote) if refspecs is not None: if not isinstance(refspecs, (list, tuple)): try: refspecs = refspecs.split(',') except AttributeError: refspecs = six.text_type(refspecs).split(',') refspecs = salt.utils.data.stringify(refspecs) command.extend(refspecs) output = _git_run(command, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, redirect_stderr=True, saltenv=saltenv, output_encoding=output_encoding)['stdout'] update_re = re.compile( r'[\s*]*(?:([0-9a-f]+)\.\.([0-9a-f]+)|' r'\[(?:new (tag|branch)|tag update)\])\s+(.+)->' ) ret = {} for line in salt.utils.itertools.split(output, '\n'): match = update_re.match(line) if match: old_sha, new_sha, new_ref_type, ref_name = \ match.groups() ref_name = ref_name.rstrip() if new_ref_type is not None: # ref is a new tag/branch ref_key = 'new tags' \ if new_ref_type == 'tag' \ else 'new branches' ret.setdefault(ref_key, []).append(ref_name) elif old_sha is not None: # ref is a branch update ret.setdefault('updated branches', {})[ref_name] = \ {'old': old_sha, 'new': new_sha} else: # ref is an updated tag ret.setdefault('updated tags', []).append(ref_name) return ret
python
def fetch(cwd, remote=None, force=False, refspecs=None, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, saltenv='base', output_encoding=None): ''' .. versionchanged:: 2015.8.2 Return data is now a dictionary containing information on branches and tags that were added/updated Interface to `git-fetch(1)`_ cwd The path to the git checkout remote Optional remote name to fetch. If not passed, then git will use its default behavior (as detailed in `git-fetch(1)`_). .. versionadded:: 2015.8.0 force Force the fetch even when it is not a fast-forward. .. versionadded:: 2015.8.0 refspecs Override the refspec(s) configured for the remote with this argument. Multiple refspecs can be passed, comma-separated. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``fetch`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-fetch(1)`: http://git-scm.com/docs/git-fetch CLI Example: .. code-block:: bash salt myminion git.fetch /path/to/repo upstream salt myminion git.fetch /path/to/repo identity=/root/.ssh/id_rsa ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('fetch') if force: command.append('--force') command.extend( [x for x in _format_opts(opts) if x not in ('-f', '--force')] ) if remote: command.append(remote) if refspecs is not None: if not isinstance(refspecs, (list, tuple)): try: refspecs = refspecs.split(',') except AttributeError: refspecs = six.text_type(refspecs).split(',') refspecs = salt.utils.data.stringify(refspecs) command.extend(refspecs) output = _git_run(command, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, redirect_stderr=True, saltenv=saltenv, output_encoding=output_encoding)['stdout'] update_re = re.compile( r'[\s*]*(?:([0-9a-f]+)\.\.([0-9a-f]+)|' r'\[(?:new (tag|branch)|tag update)\])\s+(.+)->' ) ret = {} for line in salt.utils.itertools.split(output, '\n'): match = update_re.match(line) if match: old_sha, new_sha, new_ref_type, ref_name = \ match.groups() ref_name = ref_name.rstrip() if new_ref_type is not None: # ref is a new tag/branch ref_key = 'new tags' \ if new_ref_type == 'tag' \ else 'new branches' ret.setdefault(ref_key, []).append(ref_name) elif old_sha is not None: # ref is a branch update ret.setdefault('updated branches', {})[ref_name] = \ {'old': old_sha, 'new': new_sha} else: # ref is an updated tag ret.setdefault('updated tags', []).append(ref_name) return ret
[ "def", "fetch", "(", "cwd", ",", "remote", "=", "None", ",", "force", "=", "False", ",", "refspecs", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "N...
.. versionchanged:: 2015.8.2 Return data is now a dictionary containing information on branches and tags that were added/updated Interface to `git-fetch(1)`_ cwd The path to the git checkout remote Optional remote name to fetch. If not passed, then git will use its default behavior (as detailed in `git-fetch(1)`_). .. versionadded:: 2015.8.0 force Force the fetch even when it is not a fast-forward. .. versionadded:: 2015.8.0 refspecs Override the refspec(s) configured for the remote with this argument. Multiple refspecs can be passed, comma-separated. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``fetch`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-fetch(1)`: http://git-scm.com/docs/git-fetch CLI Example: .. code-block:: bash salt myminion git.fetch /path/to/repo upstream salt myminion git.fetch /path/to/repo identity=/root/.ssh/id_rsa
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "2", "Return", "data", "is", "now", "a", "dictionary", "containing", "information", "on", "branches", "and", "tags", "that", "were", "added", "/", "updated" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L2018-L2192
train
saltstack/salt
salt/modules/git.py
init
def init(cwd, bare=False, template=None, separate_git_dir=None, shared=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-init(1)`_ cwd The path to the directory to be initialized bare : False If ``True``, init a bare repository .. versionadded:: 2015.8.0 template Set this argument to specify an alternate `template directory`_ .. versionadded:: 2015.8.0 separate_git_dir Set this argument to specify an alternate ``$GIT_DIR`` .. versionadded:: 2015.8.0 shared Set sharing permissions on git repo. See `git-init(1)`_ for more details. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``init`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-init(1)`: http://git-scm.com/docs/git-init .. _`template directory`: http://git-scm.com/docs/git-init#_template_directory CLI Examples: .. code-block:: bash salt myminion git.init /path/to/repo # Init a bare repo (before 2015.8.0) salt myminion git.init /path/to/bare/repo.git opts='--bare' # Init a bare repo (2015.8.0 and later) salt myminion git.init /path/to/bare/repo.git bare=True ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('init') if bare: command.append('--bare') if template is not None: command.append('--template={0}'.format(template)) if separate_git_dir is not None: command.append('--separate-git-dir={0}'.format(separate_git_dir)) if shared is not None: if isinstance(shared, six.integer_types) \ and not isinstance(shared, bool): shared = '0' + six.text_type(shared) elif not isinstance(shared, six.string_types): # Using lower here because booleans would be capitalized when # converted to a string. shared = six.text_type(shared).lower() command.append('--shared={0}'.format(shared)) command.extend(_format_opts(opts)) command.append(cwd) return _git_run(command, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def init(cwd, bare=False, template=None, separate_git_dir=None, shared=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-init(1)`_ cwd The path to the directory to be initialized bare : False If ``True``, init a bare repository .. versionadded:: 2015.8.0 template Set this argument to specify an alternate `template directory`_ .. versionadded:: 2015.8.0 separate_git_dir Set this argument to specify an alternate ``$GIT_DIR`` .. versionadded:: 2015.8.0 shared Set sharing permissions on git repo. See `git-init(1)`_ for more details. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``init`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-init(1)`: http://git-scm.com/docs/git-init .. _`template directory`: http://git-scm.com/docs/git-init#_template_directory CLI Examples: .. code-block:: bash salt myminion git.init /path/to/repo # Init a bare repo (before 2015.8.0) salt myminion git.init /path/to/bare/repo.git opts='--bare' # Init a bare repo (2015.8.0 and later) salt myminion git.init /path/to/bare/repo.git bare=True ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('init') if bare: command.append('--bare') if template is not None: command.append('--template={0}'.format(template)) if separate_git_dir is not None: command.append('--separate-git-dir={0}'.format(separate_git_dir)) if shared is not None: if isinstance(shared, six.integer_types) \ and not isinstance(shared, bool): shared = '0' + six.text_type(shared) elif not isinstance(shared, six.string_types): # Using lower here because booleans would be capitalized when # converted to a string. shared = six.text_type(shared).lower() command.append('--shared={0}'.format(shared)) command.extend(_format_opts(opts)) command.append(cwd) return _git_run(command, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "init", "(", "cwd", ",", "bare", "=", "False", ",", "template", "=", "None", ",", "separate_git_dir", "=", "None", ",", "shared", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "="...
Interface to `git-init(1)`_ cwd The path to the directory to be initialized bare : False If ``True``, init a bare repository .. versionadded:: 2015.8.0 template Set this argument to specify an alternate `template directory`_ .. versionadded:: 2015.8.0 separate_git_dir Set this argument to specify an alternate ``$GIT_DIR`` .. versionadded:: 2015.8.0 shared Set sharing permissions on git repo. See `git-init(1)`_ for more details. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``init`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-init(1)`: http://git-scm.com/docs/git-init .. _`template directory`: http://git-scm.com/docs/git-init#_template_directory CLI Examples: .. code-block:: bash salt myminion git.init /path/to/repo # Init a bare repo (before 2015.8.0) salt myminion git.init /path/to/bare/repo.git opts='--bare' # Init a bare repo (2015.8.0 and later) salt myminion git.init /path/to/bare/repo.git bare=True
[ "Interface", "to", "git", "-", "init", "(", "1", ")", "_" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L2195-L2317
train
saltstack/salt
salt/modules/git.py
is_worktree
def is_worktree(cwd, user=None, password=None, output_encoding=None): ''' .. versionadded:: 2015.8.0 This function will attempt to determine if ``cwd`` is part of a worktree by checking its ``.git`` to see if it is a file containing a reference to another gitdir. cwd path to the worktree to be removed user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.is_worktree /path/to/repo ''' cwd = _expand_path(cwd, user) try: toplevel = _get_toplevel(cwd, user=user, password=password, output_encoding=output_encoding) except CommandExecutionError: return False gitdir = os.path.join(toplevel, '.git') try: with salt.utils.files.fopen(gitdir, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) try: label, path = line.split(None, 1) except ValueError: return False else: # This file should only contain a single line. However, we # loop here to handle the corner case where .git is a large # binary file, so that we do not read the entire file into # memory at once. We'll hit a return statement before this # loop enters a second iteration. if label == 'gitdir:' and os.path.isabs(path): return True else: return False except IOError: return False return False
python
def is_worktree(cwd, user=None, password=None, output_encoding=None): ''' .. versionadded:: 2015.8.0 This function will attempt to determine if ``cwd`` is part of a worktree by checking its ``.git`` to see if it is a file containing a reference to another gitdir. cwd path to the worktree to be removed user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.is_worktree /path/to/repo ''' cwd = _expand_path(cwd, user) try: toplevel = _get_toplevel(cwd, user=user, password=password, output_encoding=output_encoding) except CommandExecutionError: return False gitdir = os.path.join(toplevel, '.git') try: with salt.utils.files.fopen(gitdir, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) try: label, path = line.split(None, 1) except ValueError: return False else: # This file should only contain a single line. However, we # loop here to handle the corner case where .git is a large # binary file, so that we do not read the entire file into # memory at once. We'll hit a return statement before this # loop enters a second iteration. if label == 'gitdir:' and os.path.isabs(path): return True else: return False except IOError: return False return False
[ "def", "is_worktree", "(", "cwd", ",", "user", "=", "None", ",", "password", "=", "None", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", "user", ")", "try", ":", "toplevel", "=", "_get_toplevel", "(", "cwd",...
.. versionadded:: 2015.8.0 This function will attempt to determine if ``cwd`` is part of a worktree by checking its ``.git`` to see if it is a file containing a reference to another gitdir. cwd path to the worktree to be removed user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.is_worktree /path/to/repo
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L2320-L2389
train
saltstack/salt
salt/modules/git.py
list_branches
def list_branches(cwd, remote=False, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Return a list of branches cwd The path to the git checkout remote : False If ``True``, list remote branches. Otherwise, local branches will be listed. .. warning:: This option will only return remote branches of which the local checkout is aware, use :py:func:`git.fetch <salt.modules.git.fetch>` to update remotes. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.list_branches /path/to/repo salt myminion git.list_branches /path/to/repo remote=True ''' cwd = _expand_path(cwd, user) command = ['git', 'for-each-ref', '--format', '%(refname:short)', 'refs/{0}/'.format('heads' if not remote else 'remotes')] return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout'].splitlines()
python
def list_branches(cwd, remote=False, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Return a list of branches cwd The path to the git checkout remote : False If ``True``, list remote branches. Otherwise, local branches will be listed. .. warning:: This option will only return remote branches of which the local checkout is aware, use :py:func:`git.fetch <salt.modules.git.fetch>` to update remotes. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.list_branches /path/to/repo salt myminion git.list_branches /path/to/repo remote=True ''' cwd = _expand_path(cwd, user) command = ['git', 'for-each-ref', '--format', '%(refname:short)', 'refs/{0}/'.format('heads' if not remote else 'remotes')] return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout'].splitlines()
[ "def", "list_branches", "(", "cwd", ",", "remote", "=", "False", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", "u...
.. versionadded:: 2015.8.0 Return a list of branches cwd The path to the git checkout remote : False If ``True``, list remote branches. Otherwise, local branches will be listed. .. warning:: This option will only return remote branches of which the local checkout is aware, use :py:func:`git.fetch <salt.modules.git.fetch>` to update remotes. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.list_branches /path/to/repo salt myminion git.list_branches /path/to/repo remote=True
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L2392-L2459
train
saltstack/salt
salt/modules/git.py
list_tags
def list_tags(cwd, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Return a list of tags cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.list_tags /path/to/repo ''' cwd = _expand_path(cwd, user) command = ['git', 'for-each-ref', '--format', '%(refname:short)', 'refs/tags/'] return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout'].splitlines()
python
def list_tags(cwd, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Return a list of tags cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.list_tags /path/to/repo ''' cwd = _expand_path(cwd, user) command = ['git', 'for-each-ref', '--format', '%(refname:short)', 'refs/tags/'] return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout'].splitlines()
[ "def", "list_tags", "(", "cwd", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", "user", ")", "command", "=", "[", ...
.. versionadded:: 2015.8.0 Return a list of tags cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.list_tags /path/to/repo
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L2462-L2517
train
saltstack/salt
salt/modules/git.py
list_worktrees
def list_worktrees(cwd, stale=False, user=None, password=None, output_encoding=None, **kwargs): ''' .. versionadded:: 2015.8.0 Returns information on worktrees .. versionchanged:: 2015.8.4 Version 2.7.0 added the ``list`` subcommand to `git-worktree(1)`_ which provides a lot of additional information. The return data has been changed to include this information, even for pre-2.7.0 versions of git. In addition, if a worktree has a detached head, then any tags which point to the worktree's HEAD will be included in the return data. .. note:: By default, only worktrees for which the worktree directory is still present are returned, but this can be changed using the ``all`` and ``stale`` arguments (described below). cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 all : False If ``True``, then return all worktrees tracked under $GIT_DIR/worktrees, including ones for which the gitdir is no longer present. stale : False If ``True``, return *only* worktrees whose gitdir is no longer present. .. note:: Only one of ``all`` and ``stale`` can be set to ``True``. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-worktree(1)`: http://git-scm.com/docs/git-worktree CLI Examples: .. code-block:: bash salt myminion git.list_worktrees /path/to/repo salt myminion git.list_worktrees /path/to/repo all=True salt myminion git.list_worktrees /path/to/repo stale=True ''' if not _check_worktree_support(failhard=True): return {} cwd = _expand_path(cwd, user) kwargs = salt.utils.args.clean_kwargs(**kwargs) all_ = kwargs.pop('all', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if all_ and stale: raise CommandExecutionError( '\'all\' and \'stale\' cannot both be set to True' ) def _git_tag_points_at(cwd, rev, user=None, password=None, output_encoding=None): ''' Get any tags that point at a ''' return _git_run(['git', 'tag', '--points-at', rev], cwd=cwd, user=user, password=password, output_encoding=output_encoding)['stdout'].splitlines() def _desired(is_stale, all_, stale): ''' Common logic to determine whether or not to include the worktree info in the return data. ''' if is_stale: if not all_ and not stale: # Stale worktrees are not desired, skip this one return False else: if stale: # Only stale worktrees are desired, skip this one return False return True def _duplicate_worktree_path(path): ''' Log errors to the minion log notifying of duplicate worktree paths. These should not be there, but may show up due to a bug in git 2.7.0. ''' log.error( 'git.worktree: Duplicate worktree path %s. This may be caused by ' 'a known issue in git 2.7.0 (see ' 'http://permalink.gmane.org/gmane.comp.version-control.git/283998)', path ) tracked_data_points = ('worktree', 'HEAD', 'branch') ret = {} git_version = _LooseVersion(version(versioninfo=False)) has_native_list_subcommand = git_version >= _LooseVersion('2.7.0') if has_native_list_subcommand: out = _git_run(['git', 'worktree', 'list', '--porcelain'], cwd=cwd, user=user, password=password, output_encoding=output_encoding) if out['retcode'] != 0: msg = 'Failed to list worktrees' if out['stderr']: msg += ': {0}'.format(out['stderr']) raise CommandExecutionError(msg) def _untracked_item(line): ''' Log a warning ''' log.warning('git.worktree: Untracked line item \'%s\'', line) for individual_worktree in \ salt.utils.itertools.split(out['stdout'].strip(), '\n\n'): # Initialize the dict where we're storing the tracked data points worktree_data = dict([(x, '') for x in tracked_data_points]) for line in salt.utils.itertools.split(individual_worktree, '\n'): try: type_, value = line.strip().split(None, 1) except ValueError: if line == 'detached': type_ = 'branch' value = 'detached' else: _untracked_item(line) continue if type_ not in tracked_data_points: _untracked_item(line) continue if worktree_data[type_]: log.error( 'git.worktree: Unexpected duplicate %s entry ' '\'%s\', skipping', type_, line ) continue worktree_data[type_] = value # Check for missing data points missing = [x for x in tracked_data_points if not worktree_data[x]] if missing: log.error( 'git.worktree: Incomplete worktree data, missing the ' 'following information: %s. Full data below:\n%s', ', '.join(missing), individual_worktree ) continue worktree_is_stale = not os.path.isdir(worktree_data['worktree']) if not _desired(worktree_is_stale, all_, stale): continue if worktree_data['worktree'] in ret: _duplicate_worktree_path(worktree_data['worktree']) wt_ptr = ret.setdefault(worktree_data['worktree'], {}) wt_ptr['stale'] = worktree_is_stale wt_ptr['HEAD'] = worktree_data['HEAD'] wt_ptr['detached'] = worktree_data['branch'] == 'detached' if wt_ptr['detached']: wt_ptr['branch'] = None # Check to see if HEAD points at a tag tags_found = _git_tag_points_at(cwd, wt_ptr['HEAD'], user=user, password=password, output_encoding=output_encoding) if tags_found: wt_ptr['tags'] = tags_found else: wt_ptr['branch'] = \ worktree_data['branch'].replace('refs/heads/', '', 1) return ret else: toplevel = _get_toplevel(cwd, user=user, password=password, output_encoding=output_encoding) try: worktree_root = rev_parse(cwd, opts=['--git-path', 'worktrees'], user=user, password=password, output_encoding=output_encoding) except CommandExecutionError as exc: msg = 'Failed to find worktree location for ' + cwd log.error(msg, exc_info_on_loglevel=logging.DEBUG) raise CommandExecutionError(msg) if worktree_root.startswith('.git'): worktree_root = os.path.join(cwd, worktree_root) if not os.path.isdir(worktree_root): raise CommandExecutionError( 'Worktree admin directory {0} not present'.format(worktree_root) ) def _read_file(path): ''' Return contents of a single line file with EOF newline stripped ''' try: with salt.utils.files.fopen(path, 'r') as fp_: for line in fp_: ret = salt.utils.stringutils.to_unicode(line).strip() # Ignore other lines, if they exist (which they # shouldn't) break return ret except (IOError, OSError) as exc: # Raise a CommandExecutionError salt.utils.files.process_read_exception(exc, path) for worktree_name in os.listdir(worktree_root): admin_dir = os.path.join(worktree_root, worktree_name) gitdir_file = os.path.join(admin_dir, 'gitdir') head_file = os.path.join(admin_dir, 'HEAD') wt_loc = _read_file(gitdir_file) head_ref = _read_file(head_file) if not os.path.isabs(wt_loc): log.error( 'Non-absolute path found in %s. If git 2.7.0 was ' 'installed and then downgraded, this was likely caused ' 'by a known issue in git 2.7.0. See ' 'http://permalink.gmane.org/gmane.comp.version-control' '.git/283998 for more information.', gitdir_file ) # Emulate what 'git worktree list' does under-the-hood, and # that is using the toplevel directory. It will still give # inaccurate results, but will avoid a traceback. wt_loc = toplevel if wt_loc.endswith('/.git'): wt_loc = wt_loc[:-5] worktree_is_stale = not os.path.isdir(wt_loc) if not _desired(worktree_is_stale, all_, stale): continue if wt_loc in ret: _duplicate_worktree_path(wt_loc) if head_ref.startswith('ref: '): head_ref = head_ref.split(None, 1)[-1] wt_branch = head_ref.replace('refs/heads/', '', 1) wt_head = rev_parse(cwd, rev=head_ref, user=user, password=password, output_encoding=output_encoding) wt_detached = False else: wt_branch = None wt_head = head_ref wt_detached = True wt_ptr = ret.setdefault(wt_loc, {}) wt_ptr['stale'] = worktree_is_stale wt_ptr['branch'] = wt_branch wt_ptr['HEAD'] = wt_head wt_ptr['detached'] = wt_detached # Check to see if HEAD points at a tag if wt_detached: tags_found = _git_tag_points_at(cwd, wt_head, user=user, password=password, output_encoding=output_encoding) if tags_found: wt_ptr['tags'] = tags_found return ret
python
def list_worktrees(cwd, stale=False, user=None, password=None, output_encoding=None, **kwargs): ''' .. versionadded:: 2015.8.0 Returns information on worktrees .. versionchanged:: 2015.8.4 Version 2.7.0 added the ``list`` subcommand to `git-worktree(1)`_ which provides a lot of additional information. The return data has been changed to include this information, even for pre-2.7.0 versions of git. In addition, if a worktree has a detached head, then any tags which point to the worktree's HEAD will be included in the return data. .. note:: By default, only worktrees for which the worktree directory is still present are returned, but this can be changed using the ``all`` and ``stale`` arguments (described below). cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 all : False If ``True``, then return all worktrees tracked under $GIT_DIR/worktrees, including ones for which the gitdir is no longer present. stale : False If ``True``, return *only* worktrees whose gitdir is no longer present. .. note:: Only one of ``all`` and ``stale`` can be set to ``True``. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-worktree(1)`: http://git-scm.com/docs/git-worktree CLI Examples: .. code-block:: bash salt myminion git.list_worktrees /path/to/repo salt myminion git.list_worktrees /path/to/repo all=True salt myminion git.list_worktrees /path/to/repo stale=True ''' if not _check_worktree_support(failhard=True): return {} cwd = _expand_path(cwd, user) kwargs = salt.utils.args.clean_kwargs(**kwargs) all_ = kwargs.pop('all', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if all_ and stale: raise CommandExecutionError( '\'all\' and \'stale\' cannot both be set to True' ) def _git_tag_points_at(cwd, rev, user=None, password=None, output_encoding=None): ''' Get any tags that point at a ''' return _git_run(['git', 'tag', '--points-at', rev], cwd=cwd, user=user, password=password, output_encoding=output_encoding)['stdout'].splitlines() def _desired(is_stale, all_, stale): ''' Common logic to determine whether or not to include the worktree info in the return data. ''' if is_stale: if not all_ and not stale: # Stale worktrees are not desired, skip this one return False else: if stale: # Only stale worktrees are desired, skip this one return False return True def _duplicate_worktree_path(path): ''' Log errors to the minion log notifying of duplicate worktree paths. These should not be there, but may show up due to a bug in git 2.7.0. ''' log.error( 'git.worktree: Duplicate worktree path %s. This may be caused by ' 'a known issue in git 2.7.0 (see ' 'http://permalink.gmane.org/gmane.comp.version-control.git/283998)', path ) tracked_data_points = ('worktree', 'HEAD', 'branch') ret = {} git_version = _LooseVersion(version(versioninfo=False)) has_native_list_subcommand = git_version >= _LooseVersion('2.7.0') if has_native_list_subcommand: out = _git_run(['git', 'worktree', 'list', '--porcelain'], cwd=cwd, user=user, password=password, output_encoding=output_encoding) if out['retcode'] != 0: msg = 'Failed to list worktrees' if out['stderr']: msg += ': {0}'.format(out['stderr']) raise CommandExecutionError(msg) def _untracked_item(line): ''' Log a warning ''' log.warning('git.worktree: Untracked line item \'%s\'', line) for individual_worktree in \ salt.utils.itertools.split(out['stdout'].strip(), '\n\n'): # Initialize the dict where we're storing the tracked data points worktree_data = dict([(x, '') for x in tracked_data_points]) for line in salt.utils.itertools.split(individual_worktree, '\n'): try: type_, value = line.strip().split(None, 1) except ValueError: if line == 'detached': type_ = 'branch' value = 'detached' else: _untracked_item(line) continue if type_ not in tracked_data_points: _untracked_item(line) continue if worktree_data[type_]: log.error( 'git.worktree: Unexpected duplicate %s entry ' '\'%s\', skipping', type_, line ) continue worktree_data[type_] = value # Check for missing data points missing = [x for x in tracked_data_points if not worktree_data[x]] if missing: log.error( 'git.worktree: Incomplete worktree data, missing the ' 'following information: %s. Full data below:\n%s', ', '.join(missing), individual_worktree ) continue worktree_is_stale = not os.path.isdir(worktree_data['worktree']) if not _desired(worktree_is_stale, all_, stale): continue if worktree_data['worktree'] in ret: _duplicate_worktree_path(worktree_data['worktree']) wt_ptr = ret.setdefault(worktree_data['worktree'], {}) wt_ptr['stale'] = worktree_is_stale wt_ptr['HEAD'] = worktree_data['HEAD'] wt_ptr['detached'] = worktree_data['branch'] == 'detached' if wt_ptr['detached']: wt_ptr['branch'] = None # Check to see if HEAD points at a tag tags_found = _git_tag_points_at(cwd, wt_ptr['HEAD'], user=user, password=password, output_encoding=output_encoding) if tags_found: wt_ptr['tags'] = tags_found else: wt_ptr['branch'] = \ worktree_data['branch'].replace('refs/heads/', '', 1) return ret else: toplevel = _get_toplevel(cwd, user=user, password=password, output_encoding=output_encoding) try: worktree_root = rev_parse(cwd, opts=['--git-path', 'worktrees'], user=user, password=password, output_encoding=output_encoding) except CommandExecutionError as exc: msg = 'Failed to find worktree location for ' + cwd log.error(msg, exc_info_on_loglevel=logging.DEBUG) raise CommandExecutionError(msg) if worktree_root.startswith('.git'): worktree_root = os.path.join(cwd, worktree_root) if not os.path.isdir(worktree_root): raise CommandExecutionError( 'Worktree admin directory {0} not present'.format(worktree_root) ) def _read_file(path): ''' Return contents of a single line file with EOF newline stripped ''' try: with salt.utils.files.fopen(path, 'r') as fp_: for line in fp_: ret = salt.utils.stringutils.to_unicode(line).strip() # Ignore other lines, if they exist (which they # shouldn't) break return ret except (IOError, OSError) as exc: # Raise a CommandExecutionError salt.utils.files.process_read_exception(exc, path) for worktree_name in os.listdir(worktree_root): admin_dir = os.path.join(worktree_root, worktree_name) gitdir_file = os.path.join(admin_dir, 'gitdir') head_file = os.path.join(admin_dir, 'HEAD') wt_loc = _read_file(gitdir_file) head_ref = _read_file(head_file) if not os.path.isabs(wt_loc): log.error( 'Non-absolute path found in %s. If git 2.7.0 was ' 'installed and then downgraded, this was likely caused ' 'by a known issue in git 2.7.0. See ' 'http://permalink.gmane.org/gmane.comp.version-control' '.git/283998 for more information.', gitdir_file ) # Emulate what 'git worktree list' does under-the-hood, and # that is using the toplevel directory. It will still give # inaccurate results, but will avoid a traceback. wt_loc = toplevel if wt_loc.endswith('/.git'): wt_loc = wt_loc[:-5] worktree_is_stale = not os.path.isdir(wt_loc) if not _desired(worktree_is_stale, all_, stale): continue if wt_loc in ret: _duplicate_worktree_path(wt_loc) if head_ref.startswith('ref: '): head_ref = head_ref.split(None, 1)[-1] wt_branch = head_ref.replace('refs/heads/', '', 1) wt_head = rev_parse(cwd, rev=head_ref, user=user, password=password, output_encoding=output_encoding) wt_detached = False else: wt_branch = None wt_head = head_ref wt_detached = True wt_ptr = ret.setdefault(wt_loc, {}) wt_ptr['stale'] = worktree_is_stale wt_ptr['branch'] = wt_branch wt_ptr['HEAD'] = wt_head wt_ptr['detached'] = wt_detached # Check to see if HEAD points at a tag if wt_detached: tags_found = _git_tag_points_at(cwd, wt_head, user=user, password=password, output_encoding=output_encoding) if tags_found: wt_ptr['tags'] = tags_found return ret
[ "def", "list_worktrees", "(", "cwd", ",", "stale", "=", "False", ",", "user", "=", "None", ",", "password", "=", "None", ",", "output_encoding", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "_check_worktree_support", "(", "failhard", "=",...
.. versionadded:: 2015.8.0 Returns information on worktrees .. versionchanged:: 2015.8.4 Version 2.7.0 added the ``list`` subcommand to `git-worktree(1)`_ which provides a lot of additional information. The return data has been changed to include this information, even for pre-2.7.0 versions of git. In addition, if a worktree has a detached head, then any tags which point to the worktree's HEAD will be included in the return data. .. note:: By default, only worktrees for which the worktree directory is still present are returned, but this can be changed using the ``all`` and ``stale`` arguments (described below). cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 all : False If ``True``, then return all worktrees tracked under $GIT_DIR/worktrees, including ones for which the gitdir is no longer present. stale : False If ``True``, return *only* worktrees whose gitdir is no longer present. .. note:: Only one of ``all`` and ``stale`` can be set to ``True``. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-worktree(1)`: http://git-scm.com/docs/git-worktree CLI Examples: .. code-block:: bash salt myminion git.list_worktrees /path/to/repo salt myminion git.list_worktrees /path/to/repo all=True salt myminion git.list_worktrees /path/to/repo stale=True
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L2520-L2827
train
saltstack/salt
salt/modules/git.py
ls_remote
def ls_remote(cwd=None, remote='origin', ref=None, opts='', git_opts='', user=None, password=None, identity=None, https_user=None, https_pass=None, ignore_retcode=False, output_encoding=None, saltenv='base'): ''' Interface to `git-ls-remote(1)`_. Returns the upstream hash for a remote reference. cwd The path to the git checkout. Optional (and ignored if present) when ``remote`` is set to a URL instead of a remote name. remote : origin The name of the remote to query. Can be the name of a git remote (which exists in the git checkout defined by the ``cwd`` parameter), or the URL of a remote repository. .. versionchanged:: 2015.8.0 Argument renamed from ``repository`` to ``remote`` ref The name of the ref to query. Optional, if not specified, all refs are returned. Can be a branch or tag name, or the full name of the reference (for example, to get the hash for a Github pull request number 1234, ``ref`` can be set to ``refs/pull/1234/head`` .. versionchanged:: 2015.8.0 Argument renamed from ``branch`` to ``ref`` .. versionchanged:: 2015.8.4 Defaults to returning all refs instead of master. opts Any additional options to add to the command line, in a single string .. versionadded:: 2015.8.0 git_opts Any additional options to add to git command itself (not the ``ls-remote`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-ls-remote(1)`: http://git-scm.com/docs/git-ls-remote CLI Example: .. code-block:: bash salt myminion git.ls_remote /path/to/repo origin master salt myminion git.ls_remote remote=https://mydomain.tld/repo.git ref=mytag opts='--tags' ''' if cwd is not None: cwd = _expand_path(cwd, user) try: remote = salt.utils.url.add_http_basic_auth(remote, https_user, https_pass, https_only=True) except ValueError as exc: raise SaltInvocationError(exc.__str__()) command = ['git'] + _format_git_opts(git_opts) command.append('ls-remote') command.extend(_format_opts(opts)) command.append(remote) if ref: command.append(ref) output = _git_run(command, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, saltenv=saltenv, output_encoding=output_encoding)['stdout'] ret = {} for line in output.splitlines(): try: ref_sha1, ref_name = line.split(None, 1) except IndexError: continue ret[ref_name] = ref_sha1 return ret
python
def ls_remote(cwd=None, remote='origin', ref=None, opts='', git_opts='', user=None, password=None, identity=None, https_user=None, https_pass=None, ignore_retcode=False, output_encoding=None, saltenv='base'): ''' Interface to `git-ls-remote(1)`_. Returns the upstream hash for a remote reference. cwd The path to the git checkout. Optional (and ignored if present) when ``remote`` is set to a URL instead of a remote name. remote : origin The name of the remote to query. Can be the name of a git remote (which exists in the git checkout defined by the ``cwd`` parameter), or the URL of a remote repository. .. versionchanged:: 2015.8.0 Argument renamed from ``repository`` to ``remote`` ref The name of the ref to query. Optional, if not specified, all refs are returned. Can be a branch or tag name, or the full name of the reference (for example, to get the hash for a Github pull request number 1234, ``ref`` can be set to ``refs/pull/1234/head`` .. versionchanged:: 2015.8.0 Argument renamed from ``branch`` to ``ref`` .. versionchanged:: 2015.8.4 Defaults to returning all refs instead of master. opts Any additional options to add to the command line, in a single string .. versionadded:: 2015.8.0 git_opts Any additional options to add to git command itself (not the ``ls-remote`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-ls-remote(1)`: http://git-scm.com/docs/git-ls-remote CLI Example: .. code-block:: bash salt myminion git.ls_remote /path/to/repo origin master salt myminion git.ls_remote remote=https://mydomain.tld/repo.git ref=mytag opts='--tags' ''' if cwd is not None: cwd = _expand_path(cwd, user) try: remote = salt.utils.url.add_http_basic_auth(remote, https_user, https_pass, https_only=True) except ValueError as exc: raise SaltInvocationError(exc.__str__()) command = ['git'] + _format_git_opts(git_opts) command.append('ls-remote') command.extend(_format_opts(opts)) command.append(remote) if ref: command.append(ref) output = _git_run(command, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, saltenv=saltenv, output_encoding=output_encoding)['stdout'] ret = {} for line in output.splitlines(): try: ref_sha1, ref_name = line.split(None, 1) except IndexError: continue ret[ref_name] = ref_sha1 return ret
[ "def", "ls_remote", "(", "cwd", "=", "None", ",", "remote", "=", "'origin'", ",", "ref", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "None", ",", "...
Interface to `git-ls-remote(1)`_. Returns the upstream hash for a remote reference. cwd The path to the git checkout. Optional (and ignored if present) when ``remote`` is set to a URL instead of a remote name. remote : origin The name of the remote to query. Can be the name of a git remote (which exists in the git checkout defined by the ``cwd`` parameter), or the URL of a remote repository. .. versionchanged:: 2015.8.0 Argument renamed from ``repository`` to ``remote`` ref The name of the ref to query. Optional, if not specified, all refs are returned. Can be a branch or tag name, or the full name of the reference (for example, to get the hash for a Github pull request number 1234, ``ref`` can be set to ``refs/pull/1234/head`` .. versionchanged:: 2015.8.0 Argument renamed from ``branch`` to ``ref`` .. versionchanged:: 2015.8.4 Defaults to returning all refs instead of master. opts Any additional options to add to the command line, in a single string .. versionadded:: 2015.8.0 git_opts Any additional options to add to git command itself (not the ``ls-remote`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-ls-remote(1)`: http://git-scm.com/docs/git-ls-remote CLI Example: .. code-block:: bash salt myminion git.ls_remote /path/to/repo origin master salt myminion git.ls_remote remote=https://mydomain.tld/repo.git ref=mytag opts='--tags'
[ "Interface", "to", "git", "-", "ls", "-", "remote", "(", "1", ")", "_", ".", "Returns", "the", "upstream", "hash", "for", "a", "remote", "reference", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L2830-L2992
train
saltstack/salt
salt/modules/git.py
merge
def merge(cwd, rev=None, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Interface to `git-merge(1)`_ cwd The path to the git checkout rev Revision to merge into the current branch. If not specified, the remote tracking branch will be merged. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``merge`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs. Salt will not attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. ``salt://location/identity_file``. .. note:: For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionadded:: 2018.3.5,2019.2.1,Neon ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-merge(1)`: http://git-scm.com/docs/git-merge CLI Example: .. code-block:: bash # Fetch first... salt myminion git.fetch /path/to/repo # ... then merge the remote tracking branch salt myminion git.merge /path/to/repo # .. or merge another rev salt myminion git.merge /path/to/repo rev=upstream/foo ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('merge') command.extend(_format_opts(opts)) if rev: command.append(rev) return _git_run(command, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def merge(cwd, rev=None, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Interface to `git-merge(1)`_ cwd The path to the git checkout rev Revision to merge into the current branch. If not specified, the remote tracking branch will be merged. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``merge`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs. Salt will not attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. ``salt://location/identity_file``. .. note:: For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionadded:: 2018.3.5,2019.2.1,Neon ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-merge(1)`: http://git-scm.com/docs/git-merge CLI Example: .. code-block:: bash # Fetch first... salt myminion git.fetch /path/to/repo # ... then merge the remote tracking branch salt myminion git.merge /path/to/repo # .. or merge another rev salt myminion git.merge /path/to/repo rev=upstream/foo ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('merge') command.extend(_format_opts(opts)) if rev: command.append(rev) return _git_run(command, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "merge", "(", "cwd", ",", "rev", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding"...
Interface to `git-merge(1)`_ cwd The path to the git checkout rev Revision to merge into the current branch. If not specified, the remote tracking branch will be merged. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``merge`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs. Salt will not attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. ``salt://location/identity_file``. .. note:: For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionadded:: 2018.3.5,2019.2.1,Neon ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-merge(1)`: http://git-scm.com/docs/git-merge CLI Example: .. code-block:: bash # Fetch first... salt myminion git.fetch /path/to/repo # ... then merge the remote tracking branch salt myminion git.merge /path/to/repo # .. or merge another rev salt myminion git.merge /path/to/repo rev=upstream/foo
[ "Interface", "to", "git", "-", "merge", "(", "1", ")", "_" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L2995-L3109
train
saltstack/salt
salt/modules/git.py
merge_base
def merge_base(cwd, refs=None, octopus=False, is_ancestor=False, independent=False, fork_point=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionadded:: 2015.8.0 Interface to `git-merge-base(1)`_. cwd The path to the git checkout refs Any refs/commits to check for a merge base. Can be passed as a comma-separated list or a Python list. all : False Return a list of all matching merge bases. Not compatible with any of the below options except for ``octopus``. octopus : False If ``True``, then this function will determine the best common ancestors of all specified commits, in preparation for an n-way merge. See here_ for a description of how these bases are determined. Set ``all`` to ``True`` with this option to return all computed merge bases, otherwise only the "best" will be returned. is_ancestor : False If ``True``, then instead of returning the merge base, return a boolean telling whether or not the first commit is an ancestor of the second commit. .. note:: This option requires two commits to be passed. .. versionchanged:: 2015.8.2 Works properly in git versions older than 1.8.0, where the ``--is-ancestor`` CLI option is not present. independent : False If ``True``, this function will return the IDs of the refs/commits passed which cannot be reached by another commit. fork_point If passed, then this function will return the commit where the commit diverged from the ref specified by ``fork_point``. If no fork point is found, ``None`` is returned. .. note:: At most one commit is permitted to be passed if a ``fork_point`` is specified. If no commits are passed, then ``HEAD`` is assumed. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. This option should not be necessary unless new CLI arguments are added to `git-merge-base(1)`_ and are not yet supported in Salt. git_opts Any additional options to add to git command itself (not the ``merge-base`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False if ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-merge-base(1)`: http://git-scm.com/docs/git-merge-base .. _here: http://git-scm.com/docs/git-merge-base#_discussion CLI Examples: .. code-block:: bash salt myminion git.merge_base /path/to/repo HEAD upstream/mybranch salt myminion git.merge_base /path/to/repo 8f2e542,4ad8cab,cdc9886 octopus=True salt myminion git.merge_base /path/to/repo refs=8f2e542,4ad8cab,cdc9886 independent=True salt myminion git.merge_base /path/to/repo refs=8f2e542,4ad8cab is_ancestor=True salt myminion git.merge_base /path/to/repo fork_point=upstream/master salt myminion git.merge_base /path/to/repo refs=mybranch fork_point=upstream/master ''' cwd = _expand_path(cwd, user) kwargs = salt.utils.args.clean_kwargs(**kwargs) all_ = kwargs.pop('all', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if all_ and (independent or is_ancestor or fork_point): raise SaltInvocationError( 'The \'all\' argument is not compatible with \'independent\', ' '\'is_ancestor\', or \'fork_point\'' ) if refs is None: refs = [] elif not isinstance(refs, (list, tuple)): refs = [x.strip() for x in six.text_type(refs).split(',')] mutually_exclusive_count = len( [x for x in (octopus, independent, is_ancestor, fork_point) if x] ) if mutually_exclusive_count > 1: raise SaltInvocationError( 'Only one of \'octopus\', \'independent\', \'is_ancestor\', and ' '\'fork_point\' is permitted' ) elif is_ancestor: if len(refs) != 2: raise SaltInvocationError( 'Two refs/commits are required if \'is_ancestor\' is True' ) elif fork_point: if len(refs) > 1: raise SaltInvocationError( 'At most one ref/commit can be passed if \'fork_point\' is ' 'specified' ) elif not refs: refs = ['HEAD'] if is_ancestor: if _LooseVersion(version(versioninfo=False)) < _LooseVersion('1.8.0'): # Pre 1.8.0 git doesn't have --is-ancestor, so the logic here is a # little different. First we need to resolve the first ref to a # full SHA1, and then if running git merge-base on both commits # returns an identical commit to the resolved first ref, we know # that the first ref is an ancestor of the second ref. first_commit = rev_parse(cwd, rev=refs[0], opts=['--verify'], user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) return merge_base(cwd, refs=refs, is_ancestor=False, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) == first_commit command = ['git'] + _format_git_opts(git_opts) command.append('merge-base') command.extend(_format_opts(opts)) if all_: command.append('--all') if octopus: command.append('--octopus') elif is_ancestor: command.append('--is-ancestor') elif independent: command.append('--independent') elif fork_point: command.extend(['--fork-point', fork_point]) command.extend(refs) result = _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, failhard=False if is_ancestor else True, output_encoding=output_encoding) if is_ancestor: return result['retcode'] == 0 all_bases = result['stdout'].splitlines() if all_: return all_bases return all_bases[0]
python
def merge_base(cwd, refs=None, octopus=False, is_ancestor=False, independent=False, fork_point=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionadded:: 2015.8.0 Interface to `git-merge-base(1)`_. cwd The path to the git checkout refs Any refs/commits to check for a merge base. Can be passed as a comma-separated list or a Python list. all : False Return a list of all matching merge bases. Not compatible with any of the below options except for ``octopus``. octopus : False If ``True``, then this function will determine the best common ancestors of all specified commits, in preparation for an n-way merge. See here_ for a description of how these bases are determined. Set ``all`` to ``True`` with this option to return all computed merge bases, otherwise only the "best" will be returned. is_ancestor : False If ``True``, then instead of returning the merge base, return a boolean telling whether or not the first commit is an ancestor of the second commit. .. note:: This option requires two commits to be passed. .. versionchanged:: 2015.8.2 Works properly in git versions older than 1.8.0, where the ``--is-ancestor`` CLI option is not present. independent : False If ``True``, this function will return the IDs of the refs/commits passed which cannot be reached by another commit. fork_point If passed, then this function will return the commit where the commit diverged from the ref specified by ``fork_point``. If no fork point is found, ``None`` is returned. .. note:: At most one commit is permitted to be passed if a ``fork_point`` is specified. If no commits are passed, then ``HEAD`` is assumed. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. This option should not be necessary unless new CLI arguments are added to `git-merge-base(1)`_ and are not yet supported in Salt. git_opts Any additional options to add to git command itself (not the ``merge-base`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False if ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-merge-base(1)`: http://git-scm.com/docs/git-merge-base .. _here: http://git-scm.com/docs/git-merge-base#_discussion CLI Examples: .. code-block:: bash salt myminion git.merge_base /path/to/repo HEAD upstream/mybranch salt myminion git.merge_base /path/to/repo 8f2e542,4ad8cab,cdc9886 octopus=True salt myminion git.merge_base /path/to/repo refs=8f2e542,4ad8cab,cdc9886 independent=True salt myminion git.merge_base /path/to/repo refs=8f2e542,4ad8cab is_ancestor=True salt myminion git.merge_base /path/to/repo fork_point=upstream/master salt myminion git.merge_base /path/to/repo refs=mybranch fork_point=upstream/master ''' cwd = _expand_path(cwd, user) kwargs = salt.utils.args.clean_kwargs(**kwargs) all_ = kwargs.pop('all', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if all_ and (independent or is_ancestor or fork_point): raise SaltInvocationError( 'The \'all\' argument is not compatible with \'independent\', ' '\'is_ancestor\', or \'fork_point\'' ) if refs is None: refs = [] elif not isinstance(refs, (list, tuple)): refs = [x.strip() for x in six.text_type(refs).split(',')] mutually_exclusive_count = len( [x for x in (octopus, independent, is_ancestor, fork_point) if x] ) if mutually_exclusive_count > 1: raise SaltInvocationError( 'Only one of \'octopus\', \'independent\', \'is_ancestor\', and ' '\'fork_point\' is permitted' ) elif is_ancestor: if len(refs) != 2: raise SaltInvocationError( 'Two refs/commits are required if \'is_ancestor\' is True' ) elif fork_point: if len(refs) > 1: raise SaltInvocationError( 'At most one ref/commit can be passed if \'fork_point\' is ' 'specified' ) elif not refs: refs = ['HEAD'] if is_ancestor: if _LooseVersion(version(versioninfo=False)) < _LooseVersion('1.8.0'): # Pre 1.8.0 git doesn't have --is-ancestor, so the logic here is a # little different. First we need to resolve the first ref to a # full SHA1, and then if running git merge-base on both commits # returns an identical commit to the resolved first ref, we know # that the first ref is an ancestor of the second ref. first_commit = rev_parse(cwd, rev=refs[0], opts=['--verify'], user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) return merge_base(cwd, refs=refs, is_ancestor=False, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) == first_commit command = ['git'] + _format_git_opts(git_opts) command.append('merge-base') command.extend(_format_opts(opts)) if all_: command.append('--all') if octopus: command.append('--octopus') elif is_ancestor: command.append('--is-ancestor') elif independent: command.append('--independent') elif fork_point: command.extend(['--fork-point', fork_point]) command.extend(refs) result = _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, failhard=False if is_ancestor else True, output_encoding=output_encoding) if is_ancestor: return result['retcode'] == 0 all_bases = result['stdout'].splitlines() if all_: return all_bases return all_bases[0]
[ "def", "merge_base", "(", "cwd", ",", "refs", "=", "None", ",", "octopus", "=", "False", ",", "is_ancestor", "=", "False", ",", "independent", "=", "False", ",", "fork_point", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "use...
.. versionadded:: 2015.8.0 Interface to `git-merge-base(1)`_. cwd The path to the git checkout refs Any refs/commits to check for a merge base. Can be passed as a comma-separated list or a Python list. all : False Return a list of all matching merge bases. Not compatible with any of the below options except for ``octopus``. octopus : False If ``True``, then this function will determine the best common ancestors of all specified commits, in preparation for an n-way merge. See here_ for a description of how these bases are determined. Set ``all`` to ``True`` with this option to return all computed merge bases, otherwise only the "best" will be returned. is_ancestor : False If ``True``, then instead of returning the merge base, return a boolean telling whether or not the first commit is an ancestor of the second commit. .. note:: This option requires two commits to be passed. .. versionchanged:: 2015.8.2 Works properly in git versions older than 1.8.0, where the ``--is-ancestor`` CLI option is not present. independent : False If ``True``, this function will return the IDs of the refs/commits passed which cannot be reached by another commit. fork_point If passed, then this function will return the commit where the commit diverged from the ref specified by ``fork_point``. If no fork point is found, ``None`` is returned. .. note:: At most one commit is permitted to be passed if a ``fork_point`` is specified. If no commits are passed, then ``HEAD`` is assumed. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. This option should not be necessary unless new CLI arguments are added to `git-merge-base(1)`_ and are not yet supported in Salt. git_opts Any additional options to add to git command itself (not the ``merge-base`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False if ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-merge-base(1)`: http://git-scm.com/docs/git-merge-base .. _here: http://git-scm.com/docs/git-merge-base#_discussion CLI Examples: .. code-block:: bash salt myminion git.merge_base /path/to/repo HEAD upstream/mybranch salt myminion git.merge_base /path/to/repo 8f2e542,4ad8cab,cdc9886 octopus=True salt myminion git.merge_base /path/to/repo refs=8f2e542,4ad8cab,cdc9886 independent=True salt myminion git.merge_base /path/to/repo refs=8f2e542,4ad8cab is_ancestor=True salt myminion git.merge_base /path/to/repo fork_point=upstream/master salt myminion git.merge_base /path/to/repo refs=mybranch fork_point=upstream/master
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L3112-L3322
train
saltstack/salt
salt/modules/git.py
merge_tree
def merge_tree(cwd, ref1, ref2, base=None, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Interface to `git-merge-tree(1)`_, shows the merge results and conflicts from a 3-way merge without touching the index. cwd The path to the git checkout ref1 First ref/commit to compare ref2 Second ref/commit to compare base The base tree to use for the 3-way-merge. If not provided, then :py:func:`git.merge_base <salt.modules.git.merge_base>` will be invoked on ``ref1`` and ``ref2`` to determine the merge base to use. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False if ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-merge-tree(1)`: http://git-scm.com/docs/git-merge-tree CLI Examples: .. code-block:: bash salt myminion git.merge_tree /path/to/repo HEAD upstream/dev salt myminion git.merge_tree /path/to/repo HEAD upstream/dev base=aaf3c3d ''' cwd = _expand_path(cwd, user) command = ['git', 'merge-tree'] if base is None: try: base = merge_base(cwd, refs=[ref1, ref2], output_encoding=output_encoding) except (SaltInvocationError, CommandExecutionError): raise CommandExecutionError( 'Unable to determine merge base for {0} and {1}' .format(ref1, ref2) ) command.extend([base, ref1, ref2]) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def merge_tree(cwd, ref1, ref2, base=None, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Interface to `git-merge-tree(1)`_, shows the merge results and conflicts from a 3-way merge without touching the index. cwd The path to the git checkout ref1 First ref/commit to compare ref2 Second ref/commit to compare base The base tree to use for the 3-way-merge. If not provided, then :py:func:`git.merge_base <salt.modules.git.merge_base>` will be invoked on ``ref1`` and ``ref2`` to determine the merge base to use. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False if ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-merge-tree(1)`: http://git-scm.com/docs/git-merge-tree CLI Examples: .. code-block:: bash salt myminion git.merge_tree /path/to/repo HEAD upstream/dev salt myminion git.merge_tree /path/to/repo HEAD upstream/dev base=aaf3c3d ''' cwd = _expand_path(cwd, user) command = ['git', 'merge-tree'] if base is None: try: base = merge_base(cwd, refs=[ref1, ref2], output_encoding=output_encoding) except (SaltInvocationError, CommandExecutionError): raise CommandExecutionError( 'Unable to determine merge base for {0} and {1}' .format(ref1, ref2) ) command.extend([base, ref1, ref2]) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "merge_tree", "(", "cwd", ",", "ref1", ",", "ref2", ",", "base", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path",...
.. versionadded:: 2015.8.0 Interface to `git-merge-tree(1)`_, shows the merge results and conflicts from a 3-way merge without touching the index. cwd The path to the git checkout ref1 First ref/commit to compare ref2 Second ref/commit to compare base The base tree to use for the 3-way-merge. If not provided, then :py:func:`git.merge_base <salt.modules.git.merge_base>` will be invoked on ``ref1`` and ``ref2`` to determine the merge base to use. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False if ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-merge-tree(1)`: http://git-scm.com/docs/git-merge-tree CLI Examples: .. code-block:: bash salt myminion git.merge_tree /path/to/repo HEAD upstream/dev salt myminion git.merge_tree /path/to/repo HEAD upstream/dev base=aaf3c3d
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L3325-L3405
train
saltstack/salt
salt/modules/git.py
push
def push(cwd, remote=None, ref=None, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, saltenv='base', output_encoding=None, **kwargs): ''' Interface to `git-push(1)`_ cwd The path to the git checkout remote Name of the remote to which the ref should being pushed .. versionadded:: 2015.8.0 ref : master Name of the ref to push .. note:: Being a refspec_, this argument can include a colon to define local and remote ref names. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``push`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-push(1)`: http://git-scm.com/docs/git-push .. _refspec: http://git-scm.com/book/en/v2/Git-Internals-The-Refspec CLI Example: .. code-block:: bash # Push master as origin/master salt myminion git.push /path/to/repo origin master # Push issue21 as upstream/develop salt myminion git.push /path/to/repo upstream issue21:develop # Delete remote branch 'upstream/temp' salt myminion git.push /path/to/repo upstream :temp ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('push') command.extend(_format_opts(opts)) command.extend([remote, ref]) return _git_run(command, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, saltenv=saltenv, output_encoding=output_encoding)['stdout']
python
def push(cwd, remote=None, ref=None, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, saltenv='base', output_encoding=None, **kwargs): ''' Interface to `git-push(1)`_ cwd The path to the git checkout remote Name of the remote to which the ref should being pushed .. versionadded:: 2015.8.0 ref : master Name of the ref to push .. note:: Being a refspec_, this argument can include a colon to define local and remote ref names. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``push`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-push(1)`: http://git-scm.com/docs/git-push .. _refspec: http://git-scm.com/book/en/v2/Git-Internals-The-Refspec CLI Example: .. code-block:: bash # Push master as origin/master salt myminion git.push /path/to/repo origin master # Push issue21 as upstream/develop salt myminion git.push /path/to/repo upstream issue21:develop # Delete remote branch 'upstream/temp' salt myminion git.push /path/to/repo upstream :temp ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('push') command.extend(_format_opts(opts)) command.extend([remote, ref]) return _git_run(command, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, saltenv=saltenv, output_encoding=output_encoding)['stdout']
[ "def", "push", "(", "cwd", ",", "remote", "=", "None", ",", "ref", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "None", ",", "ignore_retcode", "=", ...
Interface to `git-push(1)`_ cwd The path to the git checkout remote Name of the remote to which the ref should being pushed .. versionadded:: 2015.8.0 ref : master Name of the ref to push .. note:: Being a refspec_, this argument can include a colon to define local and remote ref names. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``push`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-push(1)`: http://git-scm.com/docs/git-push .. _refspec: http://git-scm.com/book/en/v2/Git-Internals-The-Refspec CLI Example: .. code-block:: bash # Push master as origin/master salt myminion git.push /path/to/repo origin master # Push issue21 as upstream/develop salt myminion git.push /path/to/repo upstream issue21:develop # Delete remote branch 'upstream/temp' salt myminion git.push /path/to/repo upstream :temp
[ "Interface", "to", "git", "-", "push", "(", "1", ")", "_" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L3519-L3653
train
saltstack/salt
salt/modules/git.py
rebase
def rebase(cwd, rev='master', opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-rebase(1)`_ cwd The path to the git checkout rev : master The revision to rebase onto the current branch opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``rebase`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-rebase(1)`: http://git-scm.com/docs/git-rebase CLI Example: .. code-block:: bash salt myminion git.rebase /path/to/repo master salt myminion git.rebase /path/to/repo 'origin master' salt myminion git.rebase /path/to/repo origin/master opts='--onto newbranch' ''' cwd = _expand_path(cwd, user) opts = _format_opts(opts) if any(x for x in opts if x in ('-i', '--interactive')): raise SaltInvocationError('Interactive rebases are not supported') command = ['git'] + _format_git_opts(git_opts) command.append('rebase') command.extend(opts) if not isinstance(rev, six.string_types): rev = six.text_type(rev) command.extend(salt.utils.args.shlex_split(rev)) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def rebase(cwd, rev='master', opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-rebase(1)`_ cwd The path to the git checkout rev : master The revision to rebase onto the current branch opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``rebase`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-rebase(1)`: http://git-scm.com/docs/git-rebase CLI Example: .. code-block:: bash salt myminion git.rebase /path/to/repo master salt myminion git.rebase /path/to/repo 'origin master' salt myminion git.rebase /path/to/repo origin/master opts='--onto newbranch' ''' cwd = _expand_path(cwd, user) opts = _format_opts(opts) if any(x for x in opts if x in ('-i', '--interactive')): raise SaltInvocationError('Interactive rebases are not supported') command = ['git'] + _format_git_opts(git_opts) command.append('rebase') command.extend(opts) if not isinstance(rev, six.string_types): rev = six.text_type(rev) command.extend(salt.utils.args.shlex_split(rev)) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "rebase", "(", "cwd", ",", "rev", "=", "'master'", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", ...
Interface to `git-rebase(1)`_ cwd The path to the git checkout rev : master The revision to rebase onto the current branch opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``rebase`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-rebase(1)`: http://git-scm.com/docs/git-rebase CLI Example: .. code-block:: bash salt myminion git.rebase /path/to/repo master salt myminion git.rebase /path/to/repo 'origin master' salt myminion git.rebase /path/to/repo origin/master opts='--onto newbranch'
[ "Interface", "to", "git", "-", "rebase", "(", "1", ")", "_" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L3656-L3745
train
saltstack/salt
salt/modules/git.py
remote_get
def remote_get(cwd, remote='origin', user=None, password=None, redact_auth=True, ignore_retcode=False, output_encoding=None): ''' Get the fetch and push URL for a specific remote cwd The path to the git checkout remote : origin Name of the remote to query user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 redact_auth : True Set to ``False`` to include the username/password if the remote uses HTTPS Basic Auth. Otherwise, this information will be redacted. .. warning:: Setting this to ``False`` will not only reveal any HTTPS Basic Auth that is configured, but the return data will also be written to the job cache. When possible, it is recommended to use SSH for authentication. .. versionadded:: 2015.5.6 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.remote_get /path/to/repo salt myminion git.remote_get /path/to/repo upstream ''' cwd = _expand_path(cwd, user) all_remotes = remotes(cwd, user=user, password=password, redact_auth=redact_auth, ignore_retcode=ignore_retcode, output_encoding=output_encoding) if remote not in all_remotes: raise CommandExecutionError( 'Remote \'{0}\' not present in git checkout located at {1}' .format(remote, cwd) ) return all_remotes[remote]
python
def remote_get(cwd, remote='origin', user=None, password=None, redact_auth=True, ignore_retcode=False, output_encoding=None): ''' Get the fetch and push URL for a specific remote cwd The path to the git checkout remote : origin Name of the remote to query user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 redact_auth : True Set to ``False`` to include the username/password if the remote uses HTTPS Basic Auth. Otherwise, this information will be redacted. .. warning:: Setting this to ``False`` will not only reveal any HTTPS Basic Auth that is configured, but the return data will also be written to the job cache. When possible, it is recommended to use SSH for authentication. .. versionadded:: 2015.5.6 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.remote_get /path/to/repo salt myminion git.remote_get /path/to/repo upstream ''' cwd = _expand_path(cwd, user) all_remotes = remotes(cwd, user=user, password=password, redact_auth=redact_auth, ignore_retcode=ignore_retcode, output_encoding=output_encoding) if remote not in all_remotes: raise CommandExecutionError( 'Remote \'{0}\' not present in git checkout located at {1}' .format(remote, cwd) ) return all_remotes[remote]
[ "def", "remote_get", "(", "cwd", ",", "remote", "=", "'origin'", ",", "user", "=", "None", ",", "password", "=", "None", ",", "redact_auth", "=", "True", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_...
Get the fetch and push URL for a specific remote cwd The path to the git checkout remote : origin Name of the remote to query user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 redact_auth : True Set to ``False`` to include the username/password if the remote uses HTTPS Basic Auth. Otherwise, this information will be redacted. .. warning:: Setting this to ``False`` will not only reveal any HTTPS Basic Auth that is configured, but the return data will also be written to the job cache. When possible, it is recommended to use SSH for authentication. .. versionadded:: 2015.5.6 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.remote_get /path/to/repo salt myminion git.remote_get /path/to/repo upstream
[ "Get", "the", "fetch", "and", "push", "URL", "for", "a", "specific", "remote" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L3748-L3823
train
saltstack/salt
salt/modules/git.py
remote_refs
def remote_refs(url, heads=False, tags=False, user=None, password=None, identity=None, https_user=None, https_pass=None, ignore_retcode=False, output_encoding=None, saltenv='base', **kwargs): ''' .. versionadded:: 2015.8.0 Return the remote refs for the specified URL by running ``git ls-remote``. url URL of the remote repository filter Optionally provide a ref name to ``git ls-remote``. This can be useful to make this function run faster on repositories with many branches/tags. .. versionadded:: 2019.2.0 heads : False Restrict output to heads. Can be combined with ``tags``. tags : False Restrict output to tags. Can be combined with ``heads``. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.remote_refs https://github.com/saltstack/salt.git salt myminion git.remote_refs https://github.com/saltstack/salt.git filter=develop ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) filter_ = kwargs.pop('filter', None) if kwargs: salt.utils.args.invalid_kwargs(kwargs) command = ['git', 'ls-remote'] if heads: command.append('--heads') if tags: command.append('--tags') try: command.append(salt.utils.url.add_http_basic_auth(url, https_user, https_pass, https_only=True)) except ValueError as exc: raise SaltInvocationError(exc.__str__()) if filter_: command.append(filter_) output = _git_run(command, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, saltenv=saltenv, output_encoding=output_encoding)['stdout'] ret = {} for line in salt.utils.itertools.split(output, '\n'): try: sha1_hash, ref_name = line.split(None, 1) except ValueError: continue ret[ref_name] = sha1_hash return ret
python
def remote_refs(url, heads=False, tags=False, user=None, password=None, identity=None, https_user=None, https_pass=None, ignore_retcode=False, output_encoding=None, saltenv='base', **kwargs): ''' .. versionadded:: 2015.8.0 Return the remote refs for the specified URL by running ``git ls-remote``. url URL of the remote repository filter Optionally provide a ref name to ``git ls-remote``. This can be useful to make this function run faster on repositories with many branches/tags. .. versionadded:: 2019.2.0 heads : False Restrict output to heads. Can be combined with ``tags``. tags : False Restrict output to tags. Can be combined with ``heads``. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.remote_refs https://github.com/saltstack/salt.git salt myminion git.remote_refs https://github.com/saltstack/salt.git filter=develop ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) filter_ = kwargs.pop('filter', None) if kwargs: salt.utils.args.invalid_kwargs(kwargs) command = ['git', 'ls-remote'] if heads: command.append('--heads') if tags: command.append('--tags') try: command.append(salt.utils.url.add_http_basic_auth(url, https_user, https_pass, https_only=True)) except ValueError as exc: raise SaltInvocationError(exc.__str__()) if filter_: command.append(filter_) output = _git_run(command, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, saltenv=saltenv, output_encoding=output_encoding)['stdout'] ret = {} for line in salt.utils.itertools.split(output, '\n'): try: sha1_hash, ref_name = line.split(None, 1) except ValueError: continue ret[ref_name] = sha1_hash return ret
[ "def", "remote_refs", "(", "url", ",", "heads", "=", "False", ",", "tags", "=", "False", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "None", ",", "https_user", "=", "None", ",", "https_pass", "=", "None", ",", "ignor...
.. versionadded:: 2015.8.0 Return the remote refs for the specified URL by running ``git ls-remote``. url URL of the remote repository filter Optionally provide a ref name to ``git ls-remote``. This can be useful to make this function run faster on repositories with many branches/tags. .. versionadded:: 2019.2.0 heads : False Restrict output to heads. Can be combined with ``tags``. tags : False Restrict output to tags. Can be combined with ``heads``. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.remote_refs https://github.com/saltstack/salt.git salt myminion git.remote_refs https://github.com/saltstack/salt.git filter=develop
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L3826-L3959
train
saltstack/salt
salt/modules/git.py
remote_set
def remote_set(cwd, url, remote='origin', user=None, password=None, https_user=None, https_pass=None, push_url=None, push_https_user=None, push_https_pass=None, ignore_retcode=False, output_encoding=None): ''' cwd The path to the git checkout url Remote URL to set remote : origin Name of the remote to set push_url If unset, the push URL will be identical to the fetch URL. .. versionadded:: 2015.8.0 user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 push_https_user Set HTTP Basic Auth user for ``push_url``. Ignored if ``push_url`` is unset. Only accepted for HTTPS URLs. .. versionadded:: 2015.8.0 push_https_pass Set HTTP Basic Auth password for ``push_url``. Ignored if ``push_url`` is unset. Only accepted for HTTPS URLs. .. versionadded:: 2015.8.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.remote_set /path/to/repo git@github.com:user/repo.git salt myminion git.remote_set /path/to/repo git@github.com:user/repo.git remote=upstream salt myminion git.remote_set /path/to/repo https://github.com/user/repo.git remote=upstream push_url=git@github.com:user/repo.git ''' # Check if remote exists if remote in remotes(cwd, user=user, password=password, output_encoding=output_encoding): log.debug( 'Remote \'%s\' already exists in git checkout located at %s, ' 'removing so it can be re-added', remote, cwd ) command = ['git', 'remote', 'rm', remote] _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) # Add remote try: url = salt.utils.url.add_http_basic_auth(url, https_user, https_pass, https_only=True) except ValueError as exc: raise SaltInvocationError(exc.__str__()) command = ['git', 'remote', 'add', remote, url] _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) if push_url: if not isinstance(push_url, six.string_types): push_url = six.text_type(push_url) try: push_url = salt.utils.url.add_http_basic_auth(push_url, push_https_user, push_https_pass, https_only=True) except ValueError as exc: raise SaltInvocationError(six.text_type(exc)) command = ['git', 'remote', 'set-url', '--push', remote, push_url] _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) return remote_get(cwd=cwd, remote=remote, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)
python
def remote_set(cwd, url, remote='origin', user=None, password=None, https_user=None, https_pass=None, push_url=None, push_https_user=None, push_https_pass=None, ignore_retcode=False, output_encoding=None): ''' cwd The path to the git checkout url Remote URL to set remote : origin Name of the remote to set push_url If unset, the push URL will be identical to the fetch URL. .. versionadded:: 2015.8.0 user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 push_https_user Set HTTP Basic Auth user for ``push_url``. Ignored if ``push_url`` is unset. Only accepted for HTTPS URLs. .. versionadded:: 2015.8.0 push_https_pass Set HTTP Basic Auth password for ``push_url``. Ignored if ``push_url`` is unset. Only accepted for HTTPS URLs. .. versionadded:: 2015.8.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.remote_set /path/to/repo git@github.com:user/repo.git salt myminion git.remote_set /path/to/repo git@github.com:user/repo.git remote=upstream salt myminion git.remote_set /path/to/repo https://github.com/user/repo.git remote=upstream push_url=git@github.com:user/repo.git ''' # Check if remote exists if remote in remotes(cwd, user=user, password=password, output_encoding=output_encoding): log.debug( 'Remote \'%s\' already exists in git checkout located at %s, ' 'removing so it can be re-added', remote, cwd ) command = ['git', 'remote', 'rm', remote] _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) # Add remote try: url = salt.utils.url.add_http_basic_auth(url, https_user, https_pass, https_only=True) except ValueError as exc: raise SaltInvocationError(exc.__str__()) command = ['git', 'remote', 'add', remote, url] _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) if push_url: if not isinstance(push_url, six.string_types): push_url = six.text_type(push_url) try: push_url = salt.utils.url.add_http_basic_auth(push_url, push_https_user, push_https_pass, https_only=True) except ValueError as exc: raise SaltInvocationError(six.text_type(exc)) command = ['git', 'remote', 'set-url', '--push', remote, push_url] _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding) return remote_get(cwd=cwd, remote=remote, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)
[ "def", "remote_set", "(", "cwd", ",", "url", ",", "remote", "=", "'origin'", ",", "user", "=", "None", ",", "password", "=", "None", ",", "https_user", "=", "None", ",", "https_pass", "=", "None", ",", "push_url", "=", "None", ",", "push_https_user", "...
cwd The path to the git checkout url Remote URL to set remote : origin Name of the remote to set push_url If unset, the push URL will be identical to the fetch URL. .. versionadded:: 2015.8.0 user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 https_user Set HTTP Basic Auth username. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 https_pass Set HTTP Basic Auth password. Only accepted for HTTPS URLs. .. versionadded:: 2015.5.0 push_https_user Set HTTP Basic Auth user for ``push_url``. Ignored if ``push_url`` is unset. Only accepted for HTTPS URLs. .. versionadded:: 2015.8.0 push_https_pass Set HTTP Basic Auth password for ``push_url``. Ignored if ``push_url`` is unset. Only accepted for HTTPS URLs. .. versionadded:: 2015.8.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.remote_set /path/to/repo git@github.com:user/repo.git salt myminion git.remote_set /path/to/repo git@github.com:user/repo.git remote=upstream salt myminion git.remote_set /path/to/repo https://github.com/user/repo.git remote=upstream push_url=git@github.com:user/repo.git
[ "cwd", "The", "path", "to", "the", "git", "checkout" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L3962-L4098
train
saltstack/salt
salt/modules/git.py
remotes
def remotes(cwd, user=None, password=None, redact_auth=True, ignore_retcode=False, output_encoding=None): ''' Get fetch and push URLs for each remote in a git checkout cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 redact_auth : True Set to ``False`` to include the username/password for authenticated remotes in the return data. Otherwise, this information will be redacted. .. warning:: Setting this to ``False`` will not only reveal any HTTPS Basic Auth that is configured, but the return data will also be written to the job cache. When possible, it is recommended to use SSH for authentication. .. versionadded:: 2015.5.6 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.remotes /path/to/repo ''' cwd = _expand_path(cwd, user) command = ['git', 'remote', '--verbose'] ret = {} output = _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout'] for remote_line in salt.utils.itertools.split(output, '\n'): try: remote, remote_info = remote_line.split(None, 1) except ValueError: continue try: remote_url, action = remote_info.rsplit(None, 1) except ValueError: continue # Remove parenthesis action = action.lstrip('(').rstrip(')').lower() if action not in ('fetch', 'push'): log.warning( 'Unknown action \'%s\' for remote \'%s\' in git checkout ' 'located in %s', action, remote, cwd ) continue if redact_auth: remote_url = salt.utils.url.redact_http_basic_auth(remote_url) ret.setdefault(remote, {})[action] = remote_url return ret
python
def remotes(cwd, user=None, password=None, redact_auth=True, ignore_retcode=False, output_encoding=None): ''' Get fetch and push URLs for each remote in a git checkout cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 redact_auth : True Set to ``False`` to include the username/password for authenticated remotes in the return data. Otherwise, this information will be redacted. .. warning:: Setting this to ``False`` will not only reveal any HTTPS Basic Auth that is configured, but the return data will also be written to the job cache. When possible, it is recommended to use SSH for authentication. .. versionadded:: 2015.5.6 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.remotes /path/to/repo ''' cwd = _expand_path(cwd, user) command = ['git', 'remote', '--verbose'] ret = {} output = _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout'] for remote_line in salt.utils.itertools.split(output, '\n'): try: remote, remote_info = remote_line.split(None, 1) except ValueError: continue try: remote_url, action = remote_info.rsplit(None, 1) except ValueError: continue # Remove parenthesis action = action.lstrip('(').rstrip(')').lower() if action not in ('fetch', 'push'): log.warning( 'Unknown action \'%s\' for remote \'%s\' in git checkout ' 'located in %s', action, remote, cwd ) continue if redact_auth: remote_url = salt.utils.url.redact_http_basic_auth(remote_url) ret.setdefault(remote, {})[action] = remote_url return ret
[ "def", "remotes", "(", "cwd", ",", "user", "=", "None", ",", "password", "=", "None", ",", "redact_auth", "=", "True", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", "use...
Get fetch and push URLs for each remote in a git checkout cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 redact_auth : True Set to ``False`` to include the username/password for authenticated remotes in the return data. Otherwise, this information will be redacted. .. warning:: Setting this to ``False`` will not only reveal any HTTPS Basic Auth that is configured, but the return data will also be written to the job cache. When possible, it is recommended to use SSH for authentication. .. versionadded:: 2015.5.6 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.remotes /path/to/repo
[ "Get", "fetch", "and", "push", "URLs", "for", "each", "remote", "in", "a", "git", "checkout" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L4101-L4189
train
saltstack/salt
salt/modules/git.py
reset
def reset(cwd, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-reset(1)`_, returns the stdout from the git command cwd The path to the git checkout opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``reset`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs. Salt will not attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. ``salt://location/identity_file``. .. note:: For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionadded:: 2018.3.5,2019.2.1,Neon ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-reset(1)`: http://git-scm.com/docs/git-reset CLI Examples: .. code-block:: bash # Soft reset to a specific commit ID salt myminion git.reset /path/to/repo ac3ee5c # Hard reset salt myminion git.reset /path/to/repo opts='--hard origin/master' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('reset') command.extend(_format_opts(opts)) return _git_run(command, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def reset(cwd, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-reset(1)`_, returns the stdout from the git command cwd The path to the git checkout opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``reset`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs. Salt will not attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. ``salt://location/identity_file``. .. note:: For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionadded:: 2018.3.5,2019.2.1,Neon ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-reset(1)`: http://git-scm.com/docs/git-reset CLI Examples: .. code-block:: bash # Soft reset to a specific commit ID salt myminion git.reset /path/to/repo ac3ee5c # Hard reset salt myminion git.reset /path/to/repo opts='--hard origin/master' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('reset') command.extend(_format_opts(opts)) return _git_run(command, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "reset", "(", "cwd", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", ...
Interface to `git-reset(1)`_, returns the stdout from the git command cwd The path to the git checkout opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``reset`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs. Salt will not attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. ``salt://location/identity_file``. .. note:: For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionadded:: 2018.3.5,2019.2.1,Neon ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-reset(1)`: http://git-scm.com/docs/git-reset CLI Examples: .. code-block:: bash # Soft reset to a specific commit ID salt myminion git.reset /path/to/repo ac3ee5c # Hard reset salt myminion git.reset /path/to/repo opts='--hard origin/master'
[ "Interface", "to", "git", "-", "reset", "(", "1", ")", "_", "returns", "the", "stdout", "from", "the", "git", "command" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L4192-L4289
train
saltstack/salt
salt/modules/git.py
rev_parse
def rev_parse(cwd, rev=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Interface to `git-rev-parse(1)`_ cwd The path to the git checkout rev Revision to parse. See the `SPECIFYING REVISIONS`_ section of the `git-rev-parse(1)`_ manpage for details on how to format this argument. This argument is optional when using the options in the `Options for Files` section of the `git-rev-parse(1)`_ manpage. opts Any additional options to add to the command line, in a single string git_opts Any additional options to add to git command itself (not the ``rev-parse`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-rev-parse(1)`: http://git-scm.com/docs/git-rev-parse .. _`SPECIFYING REVISIONS`: http://git-scm.com/docs/git-rev-parse#_specifying_revisions .. _`Options for Files`: http://git-scm.com/docs/git-rev-parse#_options_for_files CLI Examples: .. code-block:: bash # Get the full SHA1 for HEAD salt myminion git.rev_parse /path/to/repo HEAD # Get the short SHA1 for HEAD salt myminion git.rev_parse /path/to/repo HEAD opts='--short' # Get the develop branch's upstream tracking branch salt myminion git.rev_parse /path/to/repo 'develop@{upstream}' opts='--abbrev-ref' # Get the SHA1 for the commit corresponding to tag v1.2.3 salt myminion git.rev_parse /path/to/repo 'v1.2.3^{commit}' # Find out whether or not the repo at /path/to/repo is a bare repository salt myminion git.rev_parse /path/to/repo opts='--is-bare-repository' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('rev-parse') command.extend(_format_opts(opts)) if rev is not None: command.append(rev) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def rev_parse(cwd, rev=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Interface to `git-rev-parse(1)`_ cwd The path to the git checkout rev Revision to parse. See the `SPECIFYING REVISIONS`_ section of the `git-rev-parse(1)`_ manpage for details on how to format this argument. This argument is optional when using the options in the `Options for Files` section of the `git-rev-parse(1)`_ manpage. opts Any additional options to add to the command line, in a single string git_opts Any additional options to add to git command itself (not the ``rev-parse`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-rev-parse(1)`: http://git-scm.com/docs/git-rev-parse .. _`SPECIFYING REVISIONS`: http://git-scm.com/docs/git-rev-parse#_specifying_revisions .. _`Options for Files`: http://git-scm.com/docs/git-rev-parse#_options_for_files CLI Examples: .. code-block:: bash # Get the full SHA1 for HEAD salt myminion git.rev_parse /path/to/repo HEAD # Get the short SHA1 for HEAD salt myminion git.rev_parse /path/to/repo HEAD opts='--short' # Get the develop branch's upstream tracking branch salt myminion git.rev_parse /path/to/repo 'develop@{upstream}' opts='--abbrev-ref' # Get the SHA1 for the commit corresponding to tag v1.2.3 salt myminion git.rev_parse /path/to/repo 'v1.2.3^{commit}' # Find out whether or not the repo at /path/to/repo is a bare repository salt myminion git.rev_parse /path/to/repo opts='--is-bare-repository' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('rev-parse') command.extend(_format_opts(opts)) if rev is not None: command.append(rev) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "rev_parse", "(", "cwd", ",", "rev", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", ...
.. versionadded:: 2015.8.0 Interface to `git-rev-parse(1)`_ cwd The path to the git checkout rev Revision to parse. See the `SPECIFYING REVISIONS`_ section of the `git-rev-parse(1)`_ manpage for details on how to format this argument. This argument is optional when using the options in the `Options for Files` section of the `git-rev-parse(1)`_ manpage. opts Any additional options to add to the command line, in a single string git_opts Any additional options to add to git command itself (not the ``rev-parse`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-rev-parse(1)`: http://git-scm.com/docs/git-rev-parse .. _`SPECIFYING REVISIONS`: http://git-scm.com/docs/git-rev-parse#_specifying_revisions .. _`Options for Files`: http://git-scm.com/docs/git-rev-parse#_options_for_files CLI Examples: .. code-block:: bash # Get the full SHA1 for HEAD salt myminion git.rev_parse /path/to/repo HEAD # Get the short SHA1 for HEAD salt myminion git.rev_parse /path/to/repo HEAD opts='--short' # Get the develop branch's upstream tracking branch salt myminion git.rev_parse /path/to/repo 'develop@{upstream}' opts='--abbrev-ref' # Get the SHA1 for the commit corresponding to tag v1.2.3 salt myminion git.rev_parse /path/to/repo 'v1.2.3^{commit}' # Find out whether or not the repo at /path/to/repo is a bare repository salt myminion git.rev_parse /path/to/repo opts='--is-bare-repository'
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L4292-L4385
train
saltstack/salt
salt/modules/git.py
revision
def revision(cwd, rev='HEAD', short=False, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Returns the SHA1 hash of a given identifier (hash, branch, tag, HEAD, etc.) cwd The path to the git checkout rev : HEAD The revision short : False If ``True``, return an abbreviated SHA1 git hash user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.revision /path/to/repo mybranch ''' cwd = _expand_path(cwd, user) command = ['git', 'rev-parse'] if short: command.append('--short') command.append(rev) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def revision(cwd, rev='HEAD', short=False, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Returns the SHA1 hash of a given identifier (hash, branch, tag, HEAD, etc.) cwd The path to the git checkout rev : HEAD The revision short : False If ``True``, return an abbreviated SHA1 git hash user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.revision /path/to/repo mybranch ''' cwd = _expand_path(cwd, user) command = ['git', 'rev-parse'] if short: command.append('--short') command.append(rev) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "revision", "(", "cwd", ",", "rev", "=", "'HEAD'", ",", "short", "=", "False", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path"...
Returns the SHA1 hash of a given identifier (hash, branch, tag, HEAD, etc.) cwd The path to the git checkout rev : HEAD The revision short : False If ``True``, return an abbreviated SHA1 git hash user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.revision /path/to/repo mybranch
[ "Returns", "the", "SHA1", "hash", "of", "a", "given", "identifier", "(", "hash", "branch", "tag", "HEAD", "etc", ".", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L4388-L4451
train
saltstack/salt
salt/modules/git.py
rm_
def rm_(cwd, filename, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-rm(1)`_ cwd The path to the git checkout filename The location of the file/directory to remove, relative to ``cwd`` .. note:: To remove a directory, ``-r`` must be part of the ``opts`` parameter. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``rm`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-rm(1)`: http://git-scm.com/docs/git-rm CLI Examples: .. code-block:: bash salt myminion git.rm /path/to/repo foo/bar.py salt myminion git.rm /path/to/repo foo/bar.py opts='--dry-run' salt myminion git.rm /path/to/repo foo/baz opts='-r' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('rm') command.extend(_format_opts(opts)) command.extend(['--', filename]) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def rm_(cwd, filename, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-rm(1)`_ cwd The path to the git checkout filename The location of the file/directory to remove, relative to ``cwd`` .. note:: To remove a directory, ``-r`` must be part of the ``opts`` parameter. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``rm`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-rm(1)`: http://git-scm.com/docs/git-rm CLI Examples: .. code-block:: bash salt myminion git.rm /path/to/repo foo/bar.py salt myminion git.rm /path/to/repo foo/bar.py opts='--dry-run' salt myminion git.rm /path/to/repo foo/baz opts='-r' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('rm') command.extend(_format_opts(opts)) command.extend(['--', filename]) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "rm_", "(", "cwd", ",", "filename", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "...
Interface to `git-rm(1)`_ cwd The path to the git checkout filename The location of the file/directory to remove, relative to ``cwd`` .. note:: To remove a directory, ``-r`` must be part of the ``opts`` parameter. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``rm`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-rm(1)`: http://git-scm.com/docs/git-rm CLI Examples: .. code-block:: bash salt myminion git.rm /path/to/repo foo/bar.py salt myminion git.rm /path/to/repo foo/bar.py opts='--dry-run' salt myminion git.rm /path/to/repo foo/baz opts='-r'
[ "Interface", "to", "git", "-", "rm", "(", "1", ")", "_" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L4454-L4541
train
saltstack/salt
salt/modules/git.py
stash
def stash(cwd, action='save', opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-stash(1)`_, returns the stdout from the git command cwd The path to the git checkout opts Any additional options to add to the command line, in a single string. Use this to complete the ``git stash`` command by adding the remaining arguments (i.e. ``'save <stash comment>'``, ``'apply stash@{2}'``, ``'show'``, etc.). Omitting this argument will simply run ``git stash``. git_opts Any additional options to add to git command itself (not the ``stash`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-stash(1)`: http://git-scm.com/docs/git-stash CLI Examples: .. code-block:: bash salt myminion git.stash /path/to/repo save opts='work in progress' salt myminion git.stash /path/to/repo apply opts='stash@{1}' salt myminion git.stash /path/to/repo drop opts='stash@{1}' salt myminion git.stash /path/to/repo list ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.extend(['stash', action]) command.extend(_format_opts(opts)) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def stash(cwd, action='save', opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-stash(1)`_, returns the stdout from the git command cwd The path to the git checkout opts Any additional options to add to the command line, in a single string. Use this to complete the ``git stash`` command by adding the remaining arguments (i.e. ``'save <stash comment>'``, ``'apply stash@{2}'``, ``'show'``, etc.). Omitting this argument will simply run ``git stash``. git_opts Any additional options to add to git command itself (not the ``stash`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-stash(1)`: http://git-scm.com/docs/git-stash CLI Examples: .. code-block:: bash salt myminion git.stash /path/to/repo save opts='work in progress' salt myminion git.stash /path/to/repo apply opts='stash@{1}' salt myminion git.stash /path/to/repo drop opts='stash@{1}' salt myminion git.stash /path/to/repo list ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.extend(['stash', action]) command.extend(_format_opts(opts)) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "stash", "(", "cwd", ",", "action", "=", "'save'", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", ...
Interface to `git-stash(1)`_, returns the stdout from the git command cwd The path to the git checkout opts Any additional options to add to the command line, in a single string. Use this to complete the ``git stash`` command by adding the remaining arguments (i.e. ``'save <stash comment>'``, ``'apply stash@{2}'``, ``'show'``, etc.). Omitting this argument will simply run ``git stash``. git_opts Any additional options to add to git command itself (not the ``stash`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-stash(1)`: http://git-scm.com/docs/git-stash CLI Examples: .. code-block:: bash salt myminion git.stash /path/to/repo save opts='work in progress' salt myminion git.stash /path/to/repo apply opts='stash@{1}' salt myminion git.stash /path/to/repo drop opts='stash@{1}' salt myminion git.stash /path/to/repo list
[ "Interface", "to", "git", "-", "stash", "(", "1", ")", "_", "returns", "the", "stdout", "from", "the", "git", "command" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L4544-L4623
train
saltstack/salt
salt/modules/git.py
status
def status(cwd, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionchanged:: 2015.8.0 Return data has changed from a list of lists to a dictionary Returns the changes to the repository cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.status /path/to/repo ''' cwd = _expand_path(cwd, user) state_map = { 'M': 'modified', 'A': 'new', 'D': 'deleted', '??': 'untracked' } ret = {} command = ['git', 'status', '-z', '--porcelain'] output = _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout'] for line in output.split(str('\0')): try: state, filename = line.split(None, 1) except ValueError: continue ret.setdefault(state_map.get(state, state), []).append(filename) return ret
python
def status(cwd, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionchanged:: 2015.8.0 Return data has changed from a list of lists to a dictionary Returns the changes to the repository cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.status /path/to/repo ''' cwd = _expand_path(cwd, user) state_map = { 'M': 'modified', 'A': 'new', 'D': 'deleted', '??': 'untracked' } ret = {} command = ['git', 'status', '-z', '--porcelain'] output = _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout'] for line in output.split(str('\0')): try: state, filename = line.split(None, 1) except ValueError: continue ret.setdefault(state_map.get(state, state), []).append(filename) return ret
[ "def", "status", "(", "cwd", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", "user", ")", "state_map", "=", "{", ...
.. versionchanged:: 2015.8.0 Return data has changed from a list of lists to a dictionary Returns the changes to the repository cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt myminion git.status /path/to/repo
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "0", "Return", "data", "has", "changed", "from", "a", "list", "of", "lists", "to", "a", "dictionary" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L4626-L4695
train
saltstack/salt
salt/modules/git.py
submodule
def submodule(cwd, command, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, saltenv='base', output_encoding=None, **kwargs): ''' .. versionchanged:: 2015.8.0 Added the ``command`` argument to allow for operations other than ``update`` to be run on submodules, and deprecated the ``init`` argument. To do a submodule update with ``init=True`` moving forward, use ``command=update opts='--init'`` Interface to `git-submodule(1)`_ cwd The path to the submodule command Submodule command to run, see `git-submodule(1) <git submodule>` for more information. Any additional arguments after the command (such as the URL when adding a submodule) must be passed in the ``opts`` parameter. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``submodule`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. init : False If ``True``, ensures that new submodules are initialized .. deprecated:: 2015.8.0 Pass ``init`` as the ``command`` parameter, or include ``--init`` in the ``opts`` param with ``command`` set to update. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-submodule(1)`: http://git-scm.com/docs/git-submodule CLI Example: .. code-block:: bash # Update submodule and ensure it is initialized (before 2015.8.0) salt myminion git.submodule /path/to/repo/sub/repo init=True # Update submodule and ensure it is initialized (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo update opts='--init' # Rebase submodule (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo update opts='--rebase' # Add submodule (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo add opts='https://mydomain.tld/repo.git' # Unregister submodule (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo deinit ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) init_ = kwargs.pop('init', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cwd = _expand_path(cwd, user) if init_: raise SaltInvocationError( 'The \'init\' argument is no longer supported. Either set ' '\'command\' to \'init\', or include \'--init\' in the \'opts\' ' 'argument and set \'command\' to \'update\'.' ) cmd = ['git'] + _format_git_opts(git_opts) cmd.extend(['submodule', command]) cmd.extend(_format_opts(opts)) return _git_run(cmd, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, saltenv=saltenv, output_encoding=output_encoding)['stdout']
python
def submodule(cwd, command, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, saltenv='base', output_encoding=None, **kwargs): ''' .. versionchanged:: 2015.8.0 Added the ``command`` argument to allow for operations other than ``update`` to be run on submodules, and deprecated the ``init`` argument. To do a submodule update with ``init=True`` moving forward, use ``command=update opts='--init'`` Interface to `git-submodule(1)`_ cwd The path to the submodule command Submodule command to run, see `git-submodule(1) <git submodule>` for more information. Any additional arguments after the command (such as the URL when adding a submodule) must be passed in the ``opts`` parameter. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``submodule`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. init : False If ``True``, ensures that new submodules are initialized .. deprecated:: 2015.8.0 Pass ``init`` as the ``command`` parameter, or include ``--init`` in the ``opts`` param with ``command`` set to update. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-submodule(1)`: http://git-scm.com/docs/git-submodule CLI Example: .. code-block:: bash # Update submodule and ensure it is initialized (before 2015.8.0) salt myminion git.submodule /path/to/repo/sub/repo init=True # Update submodule and ensure it is initialized (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo update opts='--init' # Rebase submodule (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo update opts='--rebase' # Add submodule (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo add opts='https://mydomain.tld/repo.git' # Unregister submodule (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo deinit ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) init_ = kwargs.pop('init', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cwd = _expand_path(cwd, user) if init_: raise SaltInvocationError( 'The \'init\' argument is no longer supported. Either set ' '\'command\' to \'init\', or include \'--init\' in the \'opts\' ' 'argument and set \'command\' to \'update\'.' ) cmd = ['git'] + _format_git_opts(git_opts) cmd.extend(['submodule', command]) cmd.extend(_format_opts(opts)) return _git_run(cmd, cwd=cwd, user=user, password=password, identity=identity, ignore_retcode=ignore_retcode, saltenv=saltenv, output_encoding=output_encoding)['stdout']
[ "def", "submodule", "(", "cwd", ",", "command", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "None", ",", "ignore_retcode", "=", "False", ",", "saltenv", "=", "'base...
.. versionchanged:: 2015.8.0 Added the ``command`` argument to allow for operations other than ``update`` to be run on submodules, and deprecated the ``init`` argument. To do a submodule update with ``init=True`` moving forward, use ``command=update opts='--init'`` Interface to `git-submodule(1)`_ cwd The path to the submodule command Submodule command to run, see `git-submodule(1) <git submodule>` for more information. Any additional arguments after the command (such as the URL when adding a submodule) must be passed in the ``opts`` parameter. .. versionadded:: 2015.8.0 opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``submodule`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. init : False If ``True``, ensures that new submodules are initialized .. deprecated:: 2015.8.0 Pass ``init`` as the ``command`` parameter, or include ``--init`` in the ``opts`` param with ``command`` set to update. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 identity Path to a private key to use for ssh URLs .. warning:: Unless Salt is invoked from the minion using ``salt-call``, the key(s) must be passphraseless. For greater security with passphraseless private keys, see the `sshd(8)`_ manpage for information on securing the keypair from the remote side in the ``authorized_keys`` file. .. _`sshd(8)`: http://www.man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT .. versionchanged:: 2015.8.7 Salt will no longer attempt to use passphrase-protected keys unless invoked from the minion using ``salt-call``, to prevent blocking waiting for user input. Key can also be specified as a SaltStack file server URL, eg. salt://location/identity_file .. versionchanged:: 2016.3.0 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 saltenv The default salt environment to pull sls files from .. versionadded:: 2016.3.1 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-submodule(1)`: http://git-scm.com/docs/git-submodule CLI Example: .. code-block:: bash # Update submodule and ensure it is initialized (before 2015.8.0) salt myminion git.submodule /path/to/repo/sub/repo init=True # Update submodule and ensure it is initialized (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo update opts='--init' # Rebase submodule (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo update opts='--rebase' # Add submodule (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo add opts='https://mydomain.tld/repo.git' # Unregister submodule (2015.8.0 and later) salt myminion git.submodule /path/to/repo/sub/repo deinit
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "0", "Added", "the", "command", "argument", "to", "allow", "for", "operations", "other", "than", "update", "to", "be", "run", "on", "submodules", "and", "deprecated", "the", "init", "argument", ".", "To"...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L4698-L4853
train
saltstack/salt
salt/modules/git.py
symbolic_ref
def symbolic_ref(cwd, ref, value=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Interface to `git-symbolic-ref(1)`_ cwd The path to the git checkout ref Symbolic ref to read/modify value If passed, then the symbolic ref will be set to this value and an empty string will be returned. If not passed, then the ref to which ``ref`` points will be returned, unless ``--delete`` is included in ``opts`` (in which case the symbolic ref will be deleted). opts Any additional options to add to the command line, in a single string git_opts Any additional options to add to git command itself (not the ``symbolic-refs`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-symbolic-ref(1)`: http://git-scm.com/docs/git-symbolic-ref CLI Examples: .. code-block:: bash # Get ref to which HEAD is pointing salt myminion git.symbolic_ref /path/to/repo HEAD # Set/overwrite symbolic ref 'FOO' to local branch 'foo' salt myminion git.symbolic_ref /path/to/repo FOO refs/heads/foo # Delete symbolic ref 'FOO' salt myminion git.symbolic_ref /path/to/repo FOO opts='--delete' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('symbolic-ref') opts = _format_opts(opts) if value is not None and any(x in opts for x in ('-d', '--delete')): raise SaltInvocationError( 'Value cannot be set for symbolic ref if -d/--delete is included ' 'in opts' ) command.extend(opts) command.append(ref) if value: command.extend(value) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def symbolic_ref(cwd, ref, value=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Interface to `git-symbolic-ref(1)`_ cwd The path to the git checkout ref Symbolic ref to read/modify value If passed, then the symbolic ref will be set to this value and an empty string will be returned. If not passed, then the ref to which ``ref`` points will be returned, unless ``--delete`` is included in ``opts`` (in which case the symbolic ref will be deleted). opts Any additional options to add to the command line, in a single string git_opts Any additional options to add to git command itself (not the ``symbolic-refs`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-symbolic-ref(1)`: http://git-scm.com/docs/git-symbolic-ref CLI Examples: .. code-block:: bash # Get ref to which HEAD is pointing salt myminion git.symbolic_ref /path/to/repo HEAD # Set/overwrite symbolic ref 'FOO' to local branch 'foo' salt myminion git.symbolic_ref /path/to/repo FOO refs/heads/foo # Delete symbolic ref 'FOO' salt myminion git.symbolic_ref /path/to/repo FOO opts='--delete' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('symbolic-ref') opts = _format_opts(opts) if value is not None and any(x in opts for x in ('-d', '--delete')): raise SaltInvocationError( 'Value cannot be set for symbolic ref if -d/--delete is included ' 'in opts' ) command.extend(opts) command.append(ref) if value: command.extend(value) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "symbolic_ref", "(", "cwd", ",", "ref", ",", "value", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "N...
.. versionadded:: 2015.8.0 Interface to `git-symbolic-ref(1)`_ cwd The path to the git checkout ref Symbolic ref to read/modify value If passed, then the symbolic ref will be set to this value and an empty string will be returned. If not passed, then the ref to which ``ref`` points will be returned, unless ``--delete`` is included in ``opts`` (in which case the symbolic ref will be deleted). opts Any additional options to add to the command line, in a single string git_opts Any additional options to add to git command itself (not the ``symbolic-refs`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-symbolic-ref(1)`: http://git-scm.com/docs/git-symbolic-ref CLI Examples: .. code-block:: bash # Get ref to which HEAD is pointing salt myminion git.symbolic_ref /path/to/repo HEAD # Set/overwrite symbolic ref 'FOO' to local branch 'foo' salt myminion git.symbolic_ref /path/to/repo FOO refs/heads/foo # Delete symbolic ref 'FOO' salt myminion git.symbolic_ref /path/to/repo FOO opts='--delete'
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L4856-L4957
train
saltstack/salt
salt/modules/git.py
tag
def tag(cwd, name, ref='HEAD', message=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2018.3.4 Interface to `git-tag(1)`_, adds and removes tags. cwd The path to the main git checkout or a linked worktree name Name of the tag ref : HEAD Which ref to tag (defaults to local clone's HEAD) .. note:: This argument is ignored when either ``-d`` or ``--delete`` is present in the ``opts`` passed to this function. message Optional message to include with the tag. If provided, an annotated tag will be created. opts Any additional options to add to the command line, in a single string .. note:: Additionally, on the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``worktree`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. _`git-tag(1)`: http://git-scm.com/docs/git-tag CLI Example: .. code-block:: bash # Create an non-annotated tag salt myminion git.tag /path/to/repo v1.2 # Create an annotated tag salt myminion git.tag /path/to/repo v1.2 message='Version 1.2' # Delete the tag salt myminion git.tag /path/to/repo v1.2 opts='-d' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('tag') # Don't add options for annotated tags, since we'll automatically add them # if a message was passed. This keeps us from blocking on input, as passing # these options without a separate message option would launch an editor. formatted_opts = [x for x in _format_opts(opts) if x not in ('-a', '--annotate')] # Make sure that the message was not passed in the opts if any(x == '-m' or '--message' in x for x in formatted_opts): raise SaltInvocationError( 'Tag messages must be passed in the "message" argument' ) command.extend(formatted_opts) command.append(name) if '-d' not in formatted_opts and '--delete' not in formatted_opts: command.append(ref) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, redirect_stderr=True, output_encoding=output_encoding)['stdout']
python
def tag(cwd, name, ref='HEAD', message=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2018.3.4 Interface to `git-tag(1)`_, adds and removes tags. cwd The path to the main git checkout or a linked worktree name Name of the tag ref : HEAD Which ref to tag (defaults to local clone's HEAD) .. note:: This argument is ignored when either ``-d`` or ``--delete`` is present in the ``opts`` passed to this function. message Optional message to include with the tag. If provided, an annotated tag will be created. opts Any additional options to add to the command line, in a single string .. note:: Additionally, on the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``worktree`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. _`git-tag(1)`: http://git-scm.com/docs/git-tag CLI Example: .. code-block:: bash # Create an non-annotated tag salt myminion git.tag /path/to/repo v1.2 # Create an annotated tag salt myminion git.tag /path/to/repo v1.2 message='Version 1.2' # Delete the tag salt myminion git.tag /path/to/repo v1.2 opts='-d' ''' cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.append('tag') # Don't add options for annotated tags, since we'll automatically add them # if a message was passed. This keeps us from blocking on input, as passing # these options without a separate message option would launch an editor. formatted_opts = [x for x in _format_opts(opts) if x not in ('-a', '--annotate')] # Make sure that the message was not passed in the opts if any(x == '-m' or '--message' in x for x in formatted_opts): raise SaltInvocationError( 'Tag messages must be passed in the "message" argument' ) command.extend(formatted_opts) command.append(name) if '-d' not in formatted_opts and '--delete' not in formatted_opts: command.append(ref) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, redirect_stderr=True, output_encoding=output_encoding)['stdout']
[ "def", "tag", "(", "cwd", ",", "name", ",", "ref", "=", "'HEAD'", ",", "message", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "...
.. versionadded:: 2018.3.4 Interface to `git-tag(1)`_, adds and removes tags. cwd The path to the main git checkout or a linked worktree name Name of the tag ref : HEAD Which ref to tag (defaults to local clone's HEAD) .. note:: This argument is ignored when either ``-d`` or ``--delete`` is present in the ``opts`` passed to this function. message Optional message to include with the tag. If provided, an annotated tag will be created. opts Any additional options to add to the command line, in a single string .. note:: Additionally, on the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in the CLI examples below) to avoid causing errors with Salt's own argument parsing. git_opts Any additional options to add to git command itself (not the ``worktree`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. _`git-tag(1)`: http://git-scm.com/docs/git-tag CLI Example: .. code-block:: bash # Create an non-annotated tag salt myminion git.tag /path/to/repo v1.2 # Create an annotated tag salt myminion git.tag /path/to/repo v1.2 message='Version 1.2' # Delete the tag salt myminion git.tag /path/to/repo v1.2 opts='-d'
[ "..", "versionadded", "::", "2018", ".", "3", ".", "4" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L4960-L5067
train
saltstack/salt
salt/modules/git.py
version
def version(versioninfo=False): ''' .. versionadded:: 2015.8.0 Returns the version of Git installed on the minion versioninfo : False If ``True``, return the version in a versioninfo list (e.g. ``[2, 5, 0]``) CLI Example: .. code-block:: bash salt myminion git.version ''' contextkey = 'git.version' contextkey_info = 'git.versioninfo' if contextkey not in __context__: try: version_ = _git_run(['git', '--version'])['stdout'] except CommandExecutionError as exc: log.error( 'Failed to obtain the git version (error follows):\n%s', exc ) version_ = 'unknown' try: __context__[contextkey] = version_.split()[-1] except IndexError: # Somehow git --version returned no stdout while not raising an # error. Should never happen but we should still account for this # possible edge case. log.error('Running \'git --version\' returned no stdout') __context__[contextkey] = 'unknown' if not versioninfo: return __context__[contextkey] if contextkey_info not in __context__: # Set ptr to the memory location of __context__[contextkey_info] to # prevent repeated dict lookups ptr = __context__.setdefault(contextkey_info, []) for part in __context__[contextkey].split('.'): try: ptr.append(int(part)) except ValueError: ptr.append(part) return __context__[contextkey_info]
python
def version(versioninfo=False): ''' .. versionadded:: 2015.8.0 Returns the version of Git installed on the minion versioninfo : False If ``True``, return the version in a versioninfo list (e.g. ``[2, 5, 0]``) CLI Example: .. code-block:: bash salt myminion git.version ''' contextkey = 'git.version' contextkey_info = 'git.versioninfo' if contextkey not in __context__: try: version_ = _git_run(['git', '--version'])['stdout'] except CommandExecutionError as exc: log.error( 'Failed to obtain the git version (error follows):\n%s', exc ) version_ = 'unknown' try: __context__[contextkey] = version_.split()[-1] except IndexError: # Somehow git --version returned no stdout while not raising an # error. Should never happen but we should still account for this # possible edge case. log.error('Running \'git --version\' returned no stdout') __context__[contextkey] = 'unknown' if not versioninfo: return __context__[contextkey] if contextkey_info not in __context__: # Set ptr to the memory location of __context__[contextkey_info] to # prevent repeated dict lookups ptr = __context__.setdefault(contextkey_info, []) for part in __context__[contextkey].split('.'): try: ptr.append(int(part)) except ValueError: ptr.append(part) return __context__[contextkey_info]
[ "def", "version", "(", "versioninfo", "=", "False", ")", ":", "contextkey", "=", "'git.version'", "contextkey_info", "=", "'git.versioninfo'", "if", "contextkey", "not", "in", "__context__", ":", "try", ":", "version_", "=", "_git_run", "(", "[", "'git'", ",",...
.. versionadded:: 2015.8.0 Returns the version of Git installed on the minion versioninfo : False If ``True``, return the version in a versioninfo list (e.g. ``[2, 5, 0]``) CLI Example: .. code-block:: bash salt myminion git.version
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L5070-L5116
train
saltstack/salt
salt/modules/git.py
worktree_add
def worktree_add(cwd, worktree_path, ref=None, reset_branch=None, force=None, detach=False, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionadded:: 2015.8.0 Interface to `git-worktree(1)`_, adds a worktree cwd The path to the git checkout worktree_path Path to the new worktree. Can be either absolute, or relative to ``cwd``. branch Name of new branch to create. If omitted, will be set to the basename of the ``worktree_path``. For example, if the ``worktree_path`` is ``/foo/bar/baz``, then ``branch`` will be ``baz``. ref Name of the ref on which to base the new worktree. If omitted, then ``HEAD`` is use, and a new branch will be created, named for the basename of the ``worktree_path``. For example, if the ``worktree_path`` is ``/foo/bar/baz`` then a new branch ``baz`` will be created, and pointed at ``HEAD``. reset_branch : False If ``False``, then `git-worktree(1)`_ will fail to create the worktree if the targeted branch already exists. Set this argument to ``True`` to reset the targeted branch to point at ``ref``, and checkout the newly-reset branch into the new worktree. force : False By default, `git-worktree(1)`_ will not permit the same branch to be checked out in more than one worktree. Set this argument to ``True`` to override this. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` to avoid causing errors with Salt's own argument parsing. All CLI options for adding worktrees as of Git 2.5.0 are already supported by this function as of Salt 2015.8.0, so using this argument is unnecessary unless new CLI arguments are added to `git-worktree(1)`_ and are not yet supported in Salt. git_opts Any additional options to add to git command itself (not the ``worktree`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-worktree(1)`: http://git-scm.com/docs/git-worktree CLI Examples: .. code-block:: bash salt myminion git.worktree_add /path/to/repo/main ../hotfix ref=origin/master salt myminion git.worktree_add /path/to/repo/main ../hotfix branch=hotfix21 ref=v2.1.9.3 ''' _check_worktree_support() kwargs = salt.utils.args.clean_kwargs(**kwargs) branch_ = kwargs.pop('branch', None) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cwd = _expand_path(cwd, user) if branch_ and detach: raise SaltInvocationError( 'Only one of \'branch\' and \'detach\' is allowed' ) command = ['git'] + _format_git_opts(git_opts) command.extend(['worktree', 'add']) if detach: if force: log.warning( '\'force\' argument to git.worktree_add is ignored when ' 'detach=True' ) command.append('--detach') else: if not branch_: branch_ = os.path.basename(worktree_path) command.extend(['-B' if reset_branch else '-b', branch_]) if force: command.append('--force') command.extend(_format_opts(opts)) command.append(worktree_path) if ref: command.append(ref) # Checkout message goes to stderr return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, redirect_stderr=True, output_encoding=output_encoding)['stdout']
python
def worktree_add(cwd, worktree_path, ref=None, reset_branch=None, force=None, detach=False, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionadded:: 2015.8.0 Interface to `git-worktree(1)`_, adds a worktree cwd The path to the git checkout worktree_path Path to the new worktree. Can be either absolute, or relative to ``cwd``. branch Name of new branch to create. If omitted, will be set to the basename of the ``worktree_path``. For example, if the ``worktree_path`` is ``/foo/bar/baz``, then ``branch`` will be ``baz``. ref Name of the ref on which to base the new worktree. If omitted, then ``HEAD`` is use, and a new branch will be created, named for the basename of the ``worktree_path``. For example, if the ``worktree_path`` is ``/foo/bar/baz`` then a new branch ``baz`` will be created, and pointed at ``HEAD``. reset_branch : False If ``False``, then `git-worktree(1)`_ will fail to create the worktree if the targeted branch already exists. Set this argument to ``True`` to reset the targeted branch to point at ``ref``, and checkout the newly-reset branch into the new worktree. force : False By default, `git-worktree(1)`_ will not permit the same branch to be checked out in more than one worktree. Set this argument to ``True`` to override this. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` to avoid causing errors with Salt's own argument parsing. All CLI options for adding worktrees as of Git 2.5.0 are already supported by this function as of Salt 2015.8.0, so using this argument is unnecessary unless new CLI arguments are added to `git-worktree(1)`_ and are not yet supported in Salt. git_opts Any additional options to add to git command itself (not the ``worktree`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-worktree(1)`: http://git-scm.com/docs/git-worktree CLI Examples: .. code-block:: bash salt myminion git.worktree_add /path/to/repo/main ../hotfix ref=origin/master salt myminion git.worktree_add /path/to/repo/main ../hotfix branch=hotfix21 ref=v2.1.9.3 ''' _check_worktree_support() kwargs = salt.utils.args.clean_kwargs(**kwargs) branch_ = kwargs.pop('branch', None) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cwd = _expand_path(cwd, user) if branch_ and detach: raise SaltInvocationError( 'Only one of \'branch\' and \'detach\' is allowed' ) command = ['git'] + _format_git_opts(git_opts) command.extend(['worktree', 'add']) if detach: if force: log.warning( '\'force\' argument to git.worktree_add is ignored when ' 'detach=True' ) command.append('--detach') else: if not branch_: branch_ = os.path.basename(worktree_path) command.extend(['-B' if reset_branch else '-b', branch_]) if force: command.append('--force') command.extend(_format_opts(opts)) command.append(worktree_path) if ref: command.append(ref) # Checkout message goes to stderr return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, redirect_stderr=True, output_encoding=output_encoding)['stdout']
[ "def", "worktree_add", "(", "cwd", ",", "worktree_path", ",", "ref", "=", "None", ",", "reset_branch", "=", "None", ",", "force", "=", "None", ",", "detach", "=", "False", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ...
.. versionadded:: 2015.8.0 Interface to `git-worktree(1)`_, adds a worktree cwd The path to the git checkout worktree_path Path to the new worktree. Can be either absolute, or relative to ``cwd``. branch Name of new branch to create. If omitted, will be set to the basename of the ``worktree_path``. For example, if the ``worktree_path`` is ``/foo/bar/baz``, then ``branch`` will be ``baz``. ref Name of the ref on which to base the new worktree. If omitted, then ``HEAD`` is use, and a new branch will be created, named for the basename of the ``worktree_path``. For example, if the ``worktree_path`` is ``/foo/bar/baz`` then a new branch ``baz`` will be created, and pointed at ``HEAD``. reset_branch : False If ``False``, then `git-worktree(1)`_ will fail to create the worktree if the targeted branch already exists. Set this argument to ``True`` to reset the targeted branch to point at ``ref``, and checkout the newly-reset branch into the new worktree. force : False By default, `git-worktree(1)`_ will not permit the same branch to be checked out in more than one worktree. Set this argument to ``True`` to override this. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` to avoid causing errors with Salt's own argument parsing. All CLI options for adding worktrees as of Git 2.5.0 are already supported by this function as of Salt 2015.8.0, so using this argument is unnecessary unless new CLI arguments are added to `git-worktree(1)`_ and are not yet supported in Salt. git_opts Any additional options to add to git command itself (not the ``worktree`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-worktree(1)`: http://git-scm.com/docs/git-worktree CLI Examples: .. code-block:: bash salt myminion git.worktree_add /path/to/repo/main ../hotfix ref=origin/master salt myminion git.worktree_add /path/to/repo/main ../hotfix branch=hotfix21 ref=v2.1.9.3
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L5119-L5266
train
saltstack/salt
salt/modules/git.py
worktree_prune
def worktree_prune(cwd, dry_run=False, verbose=True, expire=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Interface to `git-worktree(1)`_, prunes stale worktree administrative data from the gitdir cwd The path to the main git checkout or a linked worktree dry_run : False If ``True``, then this function will report what would have been pruned, but no changes will be made. verbose : True Report all changes made. Set to ``False`` to suppress this output. expire Only prune unused worktree data older than a specific period of time. The date format for this parameter is described in the documentation for the ``gc.pruneWorktreesExpire`` config param in the `git-config(1)`_ manpage. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` to avoid causing errors with Salt's own argument parsing. All CLI options for pruning worktrees as of Git 2.5.0 are already supported by this function as of Salt 2015.8.0, so using this argument is unnecessary unless new CLI arguments are added to `git-worktree(1)`_ and are not yet supported in Salt. git_opts Any additional options to add to git command itself (not the ``worktree`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-worktree(1)`: http://git-scm.com/docs/git-worktree .. _`git-config(1)`: http://git-scm.com/docs/git-config/2.5.1 CLI Examples: .. code-block:: bash salt myminion git.worktree_prune /path/to/repo salt myminion git.worktree_prune /path/to/repo dry_run=True salt myminion git.worktree_prune /path/to/repo expire=1.day.ago ''' _check_worktree_support() cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.extend(['worktree', 'prune']) if dry_run: command.append('--dry-run') if verbose: command.append('--verbose') if expire: command.extend(['--expire', expire]) command.extend(_format_opts(opts)) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
python
def worktree_prune(cwd, dry_run=False, verbose=True, expire=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Interface to `git-worktree(1)`_, prunes stale worktree administrative data from the gitdir cwd The path to the main git checkout or a linked worktree dry_run : False If ``True``, then this function will report what would have been pruned, but no changes will be made. verbose : True Report all changes made. Set to ``False`` to suppress this output. expire Only prune unused worktree data older than a specific period of time. The date format for this parameter is described in the documentation for the ``gc.pruneWorktreesExpire`` config param in the `git-config(1)`_ manpage. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` to avoid causing errors with Salt's own argument parsing. All CLI options for pruning worktrees as of Git 2.5.0 are already supported by this function as of Salt 2015.8.0, so using this argument is unnecessary unless new CLI arguments are added to `git-worktree(1)`_ and are not yet supported in Salt. git_opts Any additional options to add to git command itself (not the ``worktree`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-worktree(1)`: http://git-scm.com/docs/git-worktree .. _`git-config(1)`: http://git-scm.com/docs/git-config/2.5.1 CLI Examples: .. code-block:: bash salt myminion git.worktree_prune /path/to/repo salt myminion git.worktree_prune /path/to/repo dry_run=True salt myminion git.worktree_prune /path/to/repo expire=1.day.ago ''' _check_worktree_support() cwd = _expand_path(cwd, user) command = ['git'] + _format_git_opts(git_opts) command.extend(['worktree', 'prune']) if dry_run: command.append('--dry-run') if verbose: command.append('--verbose') if expire: command.extend(['--expire', expire]) command.extend(_format_opts(opts)) return _git_run(command, cwd=cwd, user=user, password=password, ignore_retcode=ignore_retcode, output_encoding=output_encoding)['stdout']
[ "def", "worktree_prune", "(", "cwd", ",", "dry_run", "=", "False", ",", "verbose", "=", "True", ",", "expire", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retco...
.. versionadded:: 2015.8.0 Interface to `git-worktree(1)`_, prunes stale worktree administrative data from the gitdir cwd The path to the main git checkout or a linked worktree dry_run : False If ``True``, then this function will report what would have been pruned, but no changes will be made. verbose : True Report all changes made. Set to ``False`` to suppress this output. expire Only prune unused worktree data older than a specific period of time. The date format for this parameter is described in the documentation for the ``gc.pruneWorktreesExpire`` config param in the `git-config(1)`_ manpage. opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` to avoid causing errors with Salt's own argument parsing. All CLI options for pruning worktrees as of Git 2.5.0 are already supported by this function as of Salt 2015.8.0, so using this argument is unnecessary unless new CLI arguments are added to `git-worktree(1)`_ and are not yet supported in Salt. git_opts Any additional options to add to git command itself (not the ``worktree`` subcommand), in a single string. This is useful for passing ``-c`` to run git with temporary changes to the git configuration. .. versionadded:: 2017.7.0 .. note:: This is only supported in git 1.7.2 and newer. user User under which to run the git command. By default, the command is run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.4 ignore_retcode : False If ``True``, do not log an error to the minion log if the git command returns a nonzero exit status. .. versionadded:: 2015.8.0 output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 .. _`git-worktree(1)`: http://git-scm.com/docs/git-worktree .. _`git-config(1)`: http://git-scm.com/docs/git-config/2.5.1 CLI Examples: .. code-block:: bash salt myminion git.worktree_prune /path/to/repo salt myminion git.worktree_prune /path/to/repo dry_run=True salt myminion git.worktree_prune /path/to/repo expire=1.day.ago
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L5269-L5380
train
saltstack/salt
salt/modules/git.py
worktree_rm
def worktree_rm(cwd, user=None, output_encoding=None): ''' .. versionadded:: 2015.8.0 Recursively removes the worktree located at ``cwd``, returning ``True`` if successful. This function will attempt to determine if ``cwd`` is actually a worktree by invoking :py:func:`git.is_worktree <salt.modules.git.is_worktree>`. If the path does not correspond to a worktree, then an error will be raised and no action will be taken. .. warning:: There is no undoing this action. Be **VERY** careful before running this function. cwd Path to the worktree to be removed user Used for path expansion when ``cwd`` is not an absolute path. By default, when ``cwd`` is not absolute, the path will be assumed to be relative to the home directory of the user under which the minion is running. Setting this option will change the home directory from which path expansion is performed. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.worktree_rm /path/to/worktree ''' _check_worktree_support() cwd = _expand_path(cwd, user) if not os.path.exists(cwd): raise CommandExecutionError(cwd + ' does not exist') elif not is_worktree(cwd, output_encoding=output_encoding): raise CommandExecutionError(cwd + ' is not a git worktree') try: salt.utils.files.rm_rf(cwd) except Exception as exc: raise CommandExecutionError( 'Unable to remove {0}: {1}'.format(cwd, exc) ) return True
python
def worktree_rm(cwd, user=None, output_encoding=None): ''' .. versionadded:: 2015.8.0 Recursively removes the worktree located at ``cwd``, returning ``True`` if successful. This function will attempt to determine if ``cwd`` is actually a worktree by invoking :py:func:`git.is_worktree <salt.modules.git.is_worktree>`. If the path does not correspond to a worktree, then an error will be raised and no action will be taken. .. warning:: There is no undoing this action. Be **VERY** careful before running this function. cwd Path to the worktree to be removed user Used for path expansion when ``cwd`` is not an absolute path. By default, when ``cwd`` is not absolute, the path will be assumed to be relative to the home directory of the user under which the minion is running. Setting this option will change the home directory from which path expansion is performed. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.worktree_rm /path/to/worktree ''' _check_worktree_support() cwd = _expand_path(cwd, user) if not os.path.exists(cwd): raise CommandExecutionError(cwd + ' does not exist') elif not is_worktree(cwd, output_encoding=output_encoding): raise CommandExecutionError(cwd + ' is not a git worktree') try: salt.utils.files.rm_rf(cwd) except Exception as exc: raise CommandExecutionError( 'Unable to remove {0}: {1}'.format(cwd, exc) ) return True
[ "def", "worktree_rm", "(", "cwd", ",", "user", "=", "None", ",", "output_encoding", "=", "None", ")", ":", "_check_worktree_support", "(", ")", "cwd", "=", "_expand_path", "(", "cwd", ",", "user", ")", "if", "not", "os", ".", "path", ".", "exists", "("...
.. versionadded:: 2015.8.0 Recursively removes the worktree located at ``cwd``, returning ``True`` if successful. This function will attempt to determine if ``cwd`` is actually a worktree by invoking :py:func:`git.is_worktree <salt.modules.git.is_worktree>`. If the path does not correspond to a worktree, then an error will be raised and no action will be taken. .. warning:: There is no undoing this action. Be **VERY** careful before running this function. cwd Path to the worktree to be removed user Used for path expansion when ``cwd`` is not an absolute path. By default, when ``cwd`` is not absolute, the path will be assumed to be relative to the home directory of the user under which the minion is running. Setting this option will change the home directory from which path expansion is performed. output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. .. versionadded:: 2018.3.1 CLI Examples: .. code-block:: bash salt myminion git.worktree_rm /path/to/worktree
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L5383-L5438
train
saltstack/salt
salt/modules/archive.py
list_
def list_(name, archive_format=None, options=None, strip_components=None, clean=False, verbose=False, saltenv='base', source_hash=None): ''' .. versionadded:: 2016.11.0 .. versionchanged:: 2016.11.2 The rarfile_ Python module is now supported for listing the contents of rar archives. This is necessary on minions with older releases of the ``rar`` CLI tool, which do not support listing the contents in a parsable format. .. _rarfile: https://pypi.python.org/pypi/rarfile List the files and directories in an tar, zip, or rar archive. .. note:: This function will only provide results for XZ-compressed archives if the xz_ CLI command is available, as Python does not at this time natively support XZ compression in its tarfile_ module. Keep in mind however that most Linux distros ship with xz_ already installed. To check if a given minion has xz_, the following Salt command can be run: .. code-block:: bash salt minion_id cmd.which xz If ``None`` is returned, then xz_ is not present and must be installed. It is widely available and should be packaged as either ``xz`` or ``xz-utils``. name Path/URL of archive archive_format Specify the format of the archive (``tar``, ``zip``, or ``rar``). If this argument is omitted, the archive format will be guessed based on the value of the ``name`` parameter. options **For tar archives only.** This function will, by default, try to use the tarfile_ module from the Python standard library to get a list of files/directories. If this method fails, then it will fall back to using the shell to decompress the archive to stdout and pipe the results to ``tar -tf -`` to produce a list of filenames. XZ-compressed archives are already supported automatically, but in the event that the tar archive uses a different sort of compression not supported natively by tarfile_, this option can be used to specify a command that will decompress the archive to stdout. For example: .. code-block:: bash salt minion_id archive.list /path/to/foo.tar.gz options='gzip --decompress --stdout' .. note:: It is not necessary to manually specify options for gzip'ed archives, as gzip compression is natively supported by tarfile_. strip_components This argument specifies a number of top-level directories to strip from the results. This is similar to the paths that would be extracted if ``--strip-components`` (or ``--strip``) were used when extracting tar archives. .. versionadded:: 2016.11.2 clean : False Set this value to ``True`` to delete the path referred to by ``name`` once the contents have been listed. This option should be used with care. .. note:: If there is an error listing the archive's contents, the cached file will not be removed, to allow for troubleshooting. verbose : False If ``False``, this function will return a list of files/dirs in the archive. If ``True``, it will return a dictionary categorizing the paths into separate keys containing the directory names, file names, and also directories/files present in the top level of the archive. .. versionchanged:: 2016.11.2 This option now includes symlinks in their own list. Before, they were included with files. saltenv : base Specifies the fileserver environment from which to retrieve ``archive``. This is only applicable when ``archive`` is a file from the ``salt://`` fileserver. source_hash If ``name`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 .. _tarfile: https://docs.python.org/2/library/tarfile.html .. _xz: http://tukaani.org/xz/ CLI Examples: .. code-block:: bash salt '*' archive.list /path/to/myfile.tar.gz salt '*' archive.list /path/to/myfile.tar.gz strip_components=1 salt '*' archive.list salt://foo.tar.gz salt '*' archive.list https://domain.tld/myfile.zip salt '*' archive.list https://domain.tld/myfile.zip source_hash=f1d2d2f924e986ac86fdf7b36c94bcdf32beec15 salt '*' archive.list ftp://10.1.2.3/foo.rar ''' def _list_tar(name, cached, decompress_cmd, failhard=False): ''' List the contents of a tar archive. ''' dirs = [] files = [] links = [] try: open_kwargs = {'name': cached} \ if not isinstance(cached, subprocess.Popen) \ else {'fileobj': cached.stdout, 'mode': 'r|'} with contextlib.closing(tarfile.open(**open_kwargs)) as tar_archive: for member in tar_archive.getmembers(): _member = salt.utils.data.decode(member.name) if member.issym(): links.append(_member) elif member.isdir(): dirs.append(_member + '/') else: files.append(_member) return dirs, files, links except tarfile.ReadError: if failhard: if isinstance(cached, subprocess.Popen): stderr = cached.communicate()[1] if cached.returncode != 0: raise CommandExecutionError( 'Failed to decompress {0}'.format(name), info={'error': stderr} ) else: if not salt.utils.path.which('tar'): raise CommandExecutionError('\'tar\' command not available') if decompress_cmd is not None: # Guard against shell injection try: decompress_cmd = ' '.join( [_quote(x) for x in shlex.split(decompress_cmd)] ) except AttributeError: raise CommandExecutionError('Invalid CLI options') else: if salt.utils.path.which('xz') \ and __salt__['cmd.retcode'](['xz', '-t', cached], python_shell=False, ignore_retcode=True) == 0: decompress_cmd = 'xz --decompress --stdout' if decompress_cmd: decompressed = subprocess.Popen( '{0} {1}'.format(decompress_cmd, _quote(cached)), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return _list_tar(name, decompressed, None, True) raise CommandExecutionError( 'Unable to list contents of {0}. If this is an XZ-compressed tar ' 'archive, install XZ Utils to enable listing its contents. If it ' 'is compressed using something other than XZ, it may be necessary ' 'to specify CLI options to decompress the archive. See the ' 'documentation for details.'.format(name) ) def _list_zip(name, cached): ''' List the contents of a zip archive. Password-protected ZIP archives can still be listed by zipfile, so there is no reason to invoke the unzip command. ''' dirs = set() files = [] links = [] try: with contextlib.closing(zipfile.ZipFile(cached)) as zip_archive: for member in zip_archive.infolist(): path = member.filename if salt.utils.platform.is_windows(): if path.endswith('/'): # zipfile.ZipInfo objects on windows use forward # slash at end of the directory name. dirs.add(path) else: files.append(path) else: mode = member.external_attr >> 16 if stat.S_ISLNK(mode): links.append(path) elif stat.S_ISDIR(mode): dirs.add(path) else: files.append(path) _files = copy.deepcopy(files) for path in _files: # ZIP files created on Windows do not add entries # to the archive for directories. So, we'll need to # manually add them. dirname = ''.join(path.rpartition('/')[:2]) if dirname: dirs.add(dirname) if dirname in files: files.remove(dirname) return list(dirs), files, links except zipfile.BadZipfile: raise CommandExecutionError('{0} is not a ZIP file'.format(name)) def _list_rar(name, cached): ''' List the contents of a rar archive. ''' dirs = [] files = [] if HAS_RARFILE: with rarfile.RarFile(cached) as rf: for member in rf.infolist(): path = member.filename.replace('\\', '/') if member.isdir(): dirs.append(path + '/') else: files.append(path) else: if not salt.utils.path.which('rar'): raise CommandExecutionError( 'rar command not available, is it installed?' ) output = __salt__['cmd.run']( ['rar', 'lt', name], python_shell=False, ignore_retcode=False) matches = re.findall(r'Name:\s*([^\n]+)\s*Type:\s*([^\n]+)', output) for path, type_ in matches: if type_ == 'Directory': dirs.append(path + '/') else: files.append(path) if not dirs and not files: raise CommandExecutionError( 'Failed to list {0}, is it a rar file? If so, the ' 'installed version of rar may be too old to list data in ' 'a parsable format. Installing the rarfile Python module ' 'may be an easier workaround if newer rar is not readily ' 'available.'.format(name), info={'error': output} ) return dirs, files, [] cached = __salt__['cp.cache_file'](name, saltenv, source_hash=source_hash) if not cached: raise CommandExecutionError('Failed to cache {0}'.format(name)) try: if strip_components: try: int(strip_components) except ValueError: strip_components = -1 if strip_components <= 0: raise CommandExecutionError( '\'strip_components\' must be a positive integer' ) parsed = _urlparse(name) path = parsed.path or parsed.netloc def _unsupported_format(archive_format): ''' Raise the proper exception message for the given archive format. ''' if archive_format is None: raise CommandExecutionError( 'Unable to guess archive format, please pass an ' '\'archive_format\' argument.' ) raise CommandExecutionError( 'Unsupported archive format \'{0}\''.format(archive_format) ) if not archive_format: guessed_format = salt.utils.files.guess_archive_type(path) if guessed_format is None: _unsupported_format(archive_format) archive_format = guessed_format func = locals().get('_list_' + archive_format) if not hasattr(func, '__call__'): _unsupported_format(archive_format) args = (options,) if archive_format == 'tar' else () try: dirs, files, links = func(name, cached, *args) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to list contents of {0}: {1}'.format( name, exc.__str__() ) ) except CommandExecutionError as exc: raise except Exception as exc: raise CommandExecutionError( 'Uncaught exception \'{0}\' when listing contents of {1}' .format(exc, name) ) if clean: try: os.remove(cached) log.debug('Cleaned cached archive %s', cached) except OSError as exc: if exc.errno != errno.ENOENT: log.warning( 'Failed to clean cached archive %s: %s', cached, exc.__str__() ) if strip_components: for item in (dirs, files, links): for index, path in enumerate(item): try: # Strip off the specified number of directory # boundaries, and grab what comes after the last # stripped path separator. item[index] = item[index].split( os.sep, strip_components)[strip_components] except IndexError: # Path is excluded by strip_components because it is not # deep enough. Set this to an empty string so it can # be removed in the generator expression below. item[index] = '' # Remove all paths which were excluded item[:] = (x for x in item if x) item.sort() if verbose: ret = {'dirs': sorted(salt.utils.data.decode_list(dirs)), 'files': sorted(salt.utils.data.decode_list(files)), 'links': sorted(salt.utils.data.decode_list(links))} ret['top_level_dirs'] = [x for x in ret['dirs'] if x.count('/') == 1] ret['top_level_files'] = [x for x in ret['files'] if x.count('/') == 0] ret['top_level_links'] = [x for x in ret['links'] if x.count('/') == 0] else: ret = sorted(dirs + files + links) return ret except CommandExecutionError as exc: # Reraise with cache path in the error so that the user can examine the # cached archive for troubleshooting purposes. info = exc.info or {} info['archive location'] = cached raise CommandExecutionError(exc.error, info=info)
python
def list_(name, archive_format=None, options=None, strip_components=None, clean=False, verbose=False, saltenv='base', source_hash=None): ''' .. versionadded:: 2016.11.0 .. versionchanged:: 2016.11.2 The rarfile_ Python module is now supported for listing the contents of rar archives. This is necessary on minions with older releases of the ``rar`` CLI tool, which do not support listing the contents in a parsable format. .. _rarfile: https://pypi.python.org/pypi/rarfile List the files and directories in an tar, zip, or rar archive. .. note:: This function will only provide results for XZ-compressed archives if the xz_ CLI command is available, as Python does not at this time natively support XZ compression in its tarfile_ module. Keep in mind however that most Linux distros ship with xz_ already installed. To check if a given minion has xz_, the following Salt command can be run: .. code-block:: bash salt minion_id cmd.which xz If ``None`` is returned, then xz_ is not present and must be installed. It is widely available and should be packaged as either ``xz`` or ``xz-utils``. name Path/URL of archive archive_format Specify the format of the archive (``tar``, ``zip``, or ``rar``). If this argument is omitted, the archive format will be guessed based on the value of the ``name`` parameter. options **For tar archives only.** This function will, by default, try to use the tarfile_ module from the Python standard library to get a list of files/directories. If this method fails, then it will fall back to using the shell to decompress the archive to stdout and pipe the results to ``tar -tf -`` to produce a list of filenames. XZ-compressed archives are already supported automatically, but in the event that the tar archive uses a different sort of compression not supported natively by tarfile_, this option can be used to specify a command that will decompress the archive to stdout. For example: .. code-block:: bash salt minion_id archive.list /path/to/foo.tar.gz options='gzip --decompress --stdout' .. note:: It is not necessary to manually specify options for gzip'ed archives, as gzip compression is natively supported by tarfile_. strip_components This argument specifies a number of top-level directories to strip from the results. This is similar to the paths that would be extracted if ``--strip-components`` (or ``--strip``) were used when extracting tar archives. .. versionadded:: 2016.11.2 clean : False Set this value to ``True`` to delete the path referred to by ``name`` once the contents have been listed. This option should be used with care. .. note:: If there is an error listing the archive's contents, the cached file will not be removed, to allow for troubleshooting. verbose : False If ``False``, this function will return a list of files/dirs in the archive. If ``True``, it will return a dictionary categorizing the paths into separate keys containing the directory names, file names, and also directories/files present in the top level of the archive. .. versionchanged:: 2016.11.2 This option now includes symlinks in their own list. Before, they were included with files. saltenv : base Specifies the fileserver environment from which to retrieve ``archive``. This is only applicable when ``archive`` is a file from the ``salt://`` fileserver. source_hash If ``name`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 .. _tarfile: https://docs.python.org/2/library/tarfile.html .. _xz: http://tukaani.org/xz/ CLI Examples: .. code-block:: bash salt '*' archive.list /path/to/myfile.tar.gz salt '*' archive.list /path/to/myfile.tar.gz strip_components=1 salt '*' archive.list salt://foo.tar.gz salt '*' archive.list https://domain.tld/myfile.zip salt '*' archive.list https://domain.tld/myfile.zip source_hash=f1d2d2f924e986ac86fdf7b36c94bcdf32beec15 salt '*' archive.list ftp://10.1.2.3/foo.rar ''' def _list_tar(name, cached, decompress_cmd, failhard=False): ''' List the contents of a tar archive. ''' dirs = [] files = [] links = [] try: open_kwargs = {'name': cached} \ if not isinstance(cached, subprocess.Popen) \ else {'fileobj': cached.stdout, 'mode': 'r|'} with contextlib.closing(tarfile.open(**open_kwargs)) as tar_archive: for member in tar_archive.getmembers(): _member = salt.utils.data.decode(member.name) if member.issym(): links.append(_member) elif member.isdir(): dirs.append(_member + '/') else: files.append(_member) return dirs, files, links except tarfile.ReadError: if failhard: if isinstance(cached, subprocess.Popen): stderr = cached.communicate()[1] if cached.returncode != 0: raise CommandExecutionError( 'Failed to decompress {0}'.format(name), info={'error': stderr} ) else: if not salt.utils.path.which('tar'): raise CommandExecutionError('\'tar\' command not available') if decompress_cmd is not None: # Guard against shell injection try: decompress_cmd = ' '.join( [_quote(x) for x in shlex.split(decompress_cmd)] ) except AttributeError: raise CommandExecutionError('Invalid CLI options') else: if salt.utils.path.which('xz') \ and __salt__['cmd.retcode'](['xz', '-t', cached], python_shell=False, ignore_retcode=True) == 0: decompress_cmd = 'xz --decompress --stdout' if decompress_cmd: decompressed = subprocess.Popen( '{0} {1}'.format(decompress_cmd, _quote(cached)), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return _list_tar(name, decompressed, None, True) raise CommandExecutionError( 'Unable to list contents of {0}. If this is an XZ-compressed tar ' 'archive, install XZ Utils to enable listing its contents. If it ' 'is compressed using something other than XZ, it may be necessary ' 'to specify CLI options to decompress the archive. See the ' 'documentation for details.'.format(name) ) def _list_zip(name, cached): ''' List the contents of a zip archive. Password-protected ZIP archives can still be listed by zipfile, so there is no reason to invoke the unzip command. ''' dirs = set() files = [] links = [] try: with contextlib.closing(zipfile.ZipFile(cached)) as zip_archive: for member in zip_archive.infolist(): path = member.filename if salt.utils.platform.is_windows(): if path.endswith('/'): # zipfile.ZipInfo objects on windows use forward # slash at end of the directory name. dirs.add(path) else: files.append(path) else: mode = member.external_attr >> 16 if stat.S_ISLNK(mode): links.append(path) elif stat.S_ISDIR(mode): dirs.add(path) else: files.append(path) _files = copy.deepcopy(files) for path in _files: # ZIP files created on Windows do not add entries # to the archive for directories. So, we'll need to # manually add them. dirname = ''.join(path.rpartition('/')[:2]) if dirname: dirs.add(dirname) if dirname in files: files.remove(dirname) return list(dirs), files, links except zipfile.BadZipfile: raise CommandExecutionError('{0} is not a ZIP file'.format(name)) def _list_rar(name, cached): ''' List the contents of a rar archive. ''' dirs = [] files = [] if HAS_RARFILE: with rarfile.RarFile(cached) as rf: for member in rf.infolist(): path = member.filename.replace('\\', '/') if member.isdir(): dirs.append(path + '/') else: files.append(path) else: if not salt.utils.path.which('rar'): raise CommandExecutionError( 'rar command not available, is it installed?' ) output = __salt__['cmd.run']( ['rar', 'lt', name], python_shell=False, ignore_retcode=False) matches = re.findall(r'Name:\s*([^\n]+)\s*Type:\s*([^\n]+)', output) for path, type_ in matches: if type_ == 'Directory': dirs.append(path + '/') else: files.append(path) if not dirs and not files: raise CommandExecutionError( 'Failed to list {0}, is it a rar file? If so, the ' 'installed version of rar may be too old to list data in ' 'a parsable format. Installing the rarfile Python module ' 'may be an easier workaround if newer rar is not readily ' 'available.'.format(name), info={'error': output} ) return dirs, files, [] cached = __salt__['cp.cache_file'](name, saltenv, source_hash=source_hash) if not cached: raise CommandExecutionError('Failed to cache {0}'.format(name)) try: if strip_components: try: int(strip_components) except ValueError: strip_components = -1 if strip_components <= 0: raise CommandExecutionError( '\'strip_components\' must be a positive integer' ) parsed = _urlparse(name) path = parsed.path or parsed.netloc def _unsupported_format(archive_format): ''' Raise the proper exception message for the given archive format. ''' if archive_format is None: raise CommandExecutionError( 'Unable to guess archive format, please pass an ' '\'archive_format\' argument.' ) raise CommandExecutionError( 'Unsupported archive format \'{0}\''.format(archive_format) ) if not archive_format: guessed_format = salt.utils.files.guess_archive_type(path) if guessed_format is None: _unsupported_format(archive_format) archive_format = guessed_format func = locals().get('_list_' + archive_format) if not hasattr(func, '__call__'): _unsupported_format(archive_format) args = (options,) if archive_format == 'tar' else () try: dirs, files, links = func(name, cached, *args) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to list contents of {0}: {1}'.format( name, exc.__str__() ) ) except CommandExecutionError as exc: raise except Exception as exc: raise CommandExecutionError( 'Uncaught exception \'{0}\' when listing contents of {1}' .format(exc, name) ) if clean: try: os.remove(cached) log.debug('Cleaned cached archive %s', cached) except OSError as exc: if exc.errno != errno.ENOENT: log.warning( 'Failed to clean cached archive %s: %s', cached, exc.__str__() ) if strip_components: for item in (dirs, files, links): for index, path in enumerate(item): try: # Strip off the specified number of directory # boundaries, and grab what comes after the last # stripped path separator. item[index] = item[index].split( os.sep, strip_components)[strip_components] except IndexError: # Path is excluded by strip_components because it is not # deep enough. Set this to an empty string so it can # be removed in the generator expression below. item[index] = '' # Remove all paths which were excluded item[:] = (x for x in item if x) item.sort() if verbose: ret = {'dirs': sorted(salt.utils.data.decode_list(dirs)), 'files': sorted(salt.utils.data.decode_list(files)), 'links': sorted(salt.utils.data.decode_list(links))} ret['top_level_dirs'] = [x for x in ret['dirs'] if x.count('/') == 1] ret['top_level_files'] = [x for x in ret['files'] if x.count('/') == 0] ret['top_level_links'] = [x for x in ret['links'] if x.count('/') == 0] else: ret = sorted(dirs + files + links) return ret except CommandExecutionError as exc: # Reraise with cache path in the error so that the user can examine the # cached archive for troubleshooting purposes. info = exc.info or {} info['archive location'] = cached raise CommandExecutionError(exc.error, info=info)
[ "def", "list_", "(", "name", ",", "archive_format", "=", "None", ",", "options", "=", "None", ",", "strip_components", "=", "None", ",", "clean", "=", "False", ",", "verbose", "=", "False", ",", "saltenv", "=", "'base'", ",", "source_hash", "=", "None", ...
.. versionadded:: 2016.11.0 .. versionchanged:: 2016.11.2 The rarfile_ Python module is now supported for listing the contents of rar archives. This is necessary on minions with older releases of the ``rar`` CLI tool, which do not support listing the contents in a parsable format. .. _rarfile: https://pypi.python.org/pypi/rarfile List the files and directories in an tar, zip, or rar archive. .. note:: This function will only provide results for XZ-compressed archives if the xz_ CLI command is available, as Python does not at this time natively support XZ compression in its tarfile_ module. Keep in mind however that most Linux distros ship with xz_ already installed. To check if a given minion has xz_, the following Salt command can be run: .. code-block:: bash salt minion_id cmd.which xz If ``None`` is returned, then xz_ is not present and must be installed. It is widely available and should be packaged as either ``xz`` or ``xz-utils``. name Path/URL of archive archive_format Specify the format of the archive (``tar``, ``zip``, or ``rar``). If this argument is omitted, the archive format will be guessed based on the value of the ``name`` parameter. options **For tar archives only.** This function will, by default, try to use the tarfile_ module from the Python standard library to get a list of files/directories. If this method fails, then it will fall back to using the shell to decompress the archive to stdout and pipe the results to ``tar -tf -`` to produce a list of filenames. XZ-compressed archives are already supported automatically, but in the event that the tar archive uses a different sort of compression not supported natively by tarfile_, this option can be used to specify a command that will decompress the archive to stdout. For example: .. code-block:: bash salt minion_id archive.list /path/to/foo.tar.gz options='gzip --decompress --stdout' .. note:: It is not necessary to manually specify options for gzip'ed archives, as gzip compression is natively supported by tarfile_. strip_components This argument specifies a number of top-level directories to strip from the results. This is similar to the paths that would be extracted if ``--strip-components`` (or ``--strip``) were used when extracting tar archives. .. versionadded:: 2016.11.2 clean : False Set this value to ``True`` to delete the path referred to by ``name`` once the contents have been listed. This option should be used with care. .. note:: If there is an error listing the archive's contents, the cached file will not be removed, to allow for troubleshooting. verbose : False If ``False``, this function will return a list of files/dirs in the archive. If ``True``, it will return a dictionary categorizing the paths into separate keys containing the directory names, file names, and also directories/files present in the top level of the archive. .. versionchanged:: 2016.11.2 This option now includes symlinks in their own list. Before, they were included with files. saltenv : base Specifies the fileserver environment from which to retrieve ``archive``. This is only applicable when ``archive`` is a file from the ``salt://`` fileserver. source_hash If ``name`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 .. _tarfile: https://docs.python.org/2/library/tarfile.html .. _xz: http://tukaani.org/xz/ CLI Examples: .. code-block:: bash salt '*' archive.list /path/to/myfile.tar.gz salt '*' archive.list /path/to/myfile.tar.gz strip_components=1 salt '*' archive.list salt://foo.tar.gz salt '*' archive.list https://domain.tld/myfile.zip salt '*' archive.list https://domain.tld/myfile.zip source_hash=f1d2d2f924e986ac86fdf7b36c94bcdf32beec15 salt '*' archive.list ftp://10.1.2.3/foo.rar
[ "..", "versionadded", "::", "2016", ".", "11", ".", "0", "..", "versionchanged", "::", "2016", ".", "11", ".", "2", "The", "rarfile_", "Python", "module", "is", "now", "supported", "for", "listing", "the", "contents", "of", "rar", "archives", ".", "This"...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L58-L432
train
saltstack/salt
salt/modules/archive.py
_expand_sources
def _expand_sources(sources): ''' Expands a user-provided specification of source files into a list of paths. ''' if sources is None: return [] if isinstance(sources, six.string_types): sources = [x.strip() for x in sources.split(',')] elif isinstance(sources, (float, six.integer_types)): sources = [six.text_type(sources)] return [path for source in sources for path in _glob(source)]
python
def _expand_sources(sources): ''' Expands a user-provided specification of source files into a list of paths. ''' if sources is None: return [] if isinstance(sources, six.string_types): sources = [x.strip() for x in sources.split(',')] elif isinstance(sources, (float, six.integer_types)): sources = [six.text_type(sources)] return [path for source in sources for path in _glob(source)]
[ "def", "_expand_sources", "(", "sources", ")", ":", "if", "sources", "is", "None", ":", "return", "[", "]", "if", "isinstance", "(", "sources", ",", "six", ".", "string_types", ")", ":", "sources", "=", "[", "x", ".", "strip", "(", ")", "for", "x", ...
Expands a user-provided specification of source files into a list of paths.
[ "Expands", "a", "user", "-", "provided", "specification", "of", "source", "files", "into", "a", "list", "of", "paths", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L450-L462
train
saltstack/salt
salt/modules/archive.py
tar
def tar(options, tarfile, sources=None, dest=None, cwd=None, template=None, runas=None): ''' .. note:: This function has changed for version 0.17.0. In prior versions, the ``cwd`` and ``template`` arguments must be specified, with the source directories/files coming as a space-separated list at the end of the command. Beginning with 0.17.0, ``sources`` must be a comma-separated list, and the ``cwd`` and ``template`` arguments are optional. Uses the tar command to pack, unpack, etc. tar files options Options to pass to the tar command .. versionchanged:: 2015.8.0 The mandatory `-` prefixing has been removed. An options string beginning with a `--long-option`, would have uncharacteristically needed its first `-` removed under the former scheme. Also, tar will parse its options differently if short options are used with or without a preceding `-`, so it is better to not confuse the user into thinking they're using the non-`-` format, when really they are using the with-`-` format. tarfile The filename of the tar archive to pack/unpack sources Comma delimited list of files to **pack** into the tarfile. Can also be passed as a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument dest The destination directory into which to **unpack** the tarfile cwd : None The directory in which the tar command should be executed. If not specified, will default to the home directory of the user under which the salt minion process is running. template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.tar cjvf /tmp/salt.tar.bz2 {{grains.saltpath}} template=jinja CLI Examples: .. code-block:: bash # Create a tarfile salt '*' archive.tar cjvf /tmp/tarfile.tar.bz2 /tmp/file_1,/tmp/file_2 # Create a tarfile using globbing (2017.7.0 and later) salt '*' archive.tar cjvf /tmp/tarfile.tar.bz2 '/tmp/file_*' # Unpack a tarfile salt '*' archive.tar xf foo.tar dest=/target/directory ''' if not options: # Catch instances were people pass an empty string for the "options" # argument. Someone would have to be really silly to do this, but we # should at least let them know of their silliness. raise SaltInvocationError('Tar options can not be empty') cmd = ['tar'] if options: cmd.extend(options.split()) cmd.extend(['{0}'.format(tarfile)]) cmd.extend(_expand_sources(sources)) if dest: cmd.extend(['-C', '{0}'.format(dest)]) return __salt__['cmd.run'](cmd, cwd=cwd, template=template, runas=runas, python_shell=False).splitlines()
python
def tar(options, tarfile, sources=None, dest=None, cwd=None, template=None, runas=None): ''' .. note:: This function has changed for version 0.17.0. In prior versions, the ``cwd`` and ``template`` arguments must be specified, with the source directories/files coming as a space-separated list at the end of the command. Beginning with 0.17.0, ``sources`` must be a comma-separated list, and the ``cwd`` and ``template`` arguments are optional. Uses the tar command to pack, unpack, etc. tar files options Options to pass to the tar command .. versionchanged:: 2015.8.0 The mandatory `-` prefixing has been removed. An options string beginning with a `--long-option`, would have uncharacteristically needed its first `-` removed under the former scheme. Also, tar will parse its options differently if short options are used with or without a preceding `-`, so it is better to not confuse the user into thinking they're using the non-`-` format, when really they are using the with-`-` format. tarfile The filename of the tar archive to pack/unpack sources Comma delimited list of files to **pack** into the tarfile. Can also be passed as a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument dest The destination directory into which to **unpack** the tarfile cwd : None The directory in which the tar command should be executed. If not specified, will default to the home directory of the user under which the salt minion process is running. template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.tar cjvf /tmp/salt.tar.bz2 {{grains.saltpath}} template=jinja CLI Examples: .. code-block:: bash # Create a tarfile salt '*' archive.tar cjvf /tmp/tarfile.tar.bz2 /tmp/file_1,/tmp/file_2 # Create a tarfile using globbing (2017.7.0 and later) salt '*' archive.tar cjvf /tmp/tarfile.tar.bz2 '/tmp/file_*' # Unpack a tarfile salt '*' archive.tar xf foo.tar dest=/target/directory ''' if not options: # Catch instances were people pass an empty string for the "options" # argument. Someone would have to be really silly to do this, but we # should at least let them know of their silliness. raise SaltInvocationError('Tar options can not be empty') cmd = ['tar'] if options: cmd.extend(options.split()) cmd.extend(['{0}'.format(tarfile)]) cmd.extend(_expand_sources(sources)) if dest: cmd.extend(['-C', '{0}'.format(dest)]) return __salt__['cmd.run'](cmd, cwd=cwd, template=template, runas=runas, python_shell=False).splitlines()
[ "def", "tar", "(", "options", ",", "tarfile", ",", "sources", "=", "None", ",", "dest", "=", "None", ",", "cwd", "=", "None", ",", "template", "=", "None", ",", "runas", "=", "None", ")", ":", "if", "not", "options", ":", "# Catch instances were people...
.. note:: This function has changed for version 0.17.0. In prior versions, the ``cwd`` and ``template`` arguments must be specified, with the source directories/files coming as a space-separated list at the end of the command. Beginning with 0.17.0, ``sources`` must be a comma-separated list, and the ``cwd`` and ``template`` arguments are optional. Uses the tar command to pack, unpack, etc. tar files options Options to pass to the tar command .. versionchanged:: 2015.8.0 The mandatory `-` prefixing has been removed. An options string beginning with a `--long-option`, would have uncharacteristically needed its first `-` removed under the former scheme. Also, tar will parse its options differently if short options are used with or without a preceding `-`, so it is better to not confuse the user into thinking they're using the non-`-` format, when really they are using the with-`-` format. tarfile The filename of the tar archive to pack/unpack sources Comma delimited list of files to **pack** into the tarfile. Can also be passed as a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument dest The destination directory into which to **unpack** the tarfile cwd : None The directory in which the tar command should be executed. If not specified, will default to the home directory of the user under which the salt minion process is running. template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.tar cjvf /tmp/salt.tar.bz2 {{grains.saltpath}} template=jinja CLI Examples: .. code-block:: bash # Create a tarfile salt '*' archive.tar cjvf /tmp/tarfile.tar.bz2 /tmp/file_1,/tmp/file_2 # Create a tarfile using globbing (2017.7.0 and later) salt '*' archive.tar cjvf /tmp/tarfile.tar.bz2 '/tmp/file_*' # Unpack a tarfile salt '*' archive.tar xf foo.tar dest=/target/directory
[ "..", "note", "::" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L466-L550
train
saltstack/salt
salt/modules/archive.py
gzip
def gzip(sourcefile, template=None, runas=None, options=None): ''' Uses the gzip command to create gzip files template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.gzip template=jinja /tmp/{{grains.id}}.txt runas : None The user with which to run the gzip command line options : None Pass any additional arguments to gzip .. versionadded:: 2016.3.4 CLI Example: .. code-block:: bash # Create /tmp/sourcefile.txt.gz salt '*' archive.gzip /tmp/sourcefile.txt salt '*' archive.gzip /tmp/sourcefile.txt options='-9 --verbose' ''' cmd = ['gzip'] if options: cmd.append(options) cmd.append('{0}'.format(sourcefile)) return __salt__['cmd.run'](cmd, template=template, runas=runas, python_shell=False).splitlines()
python
def gzip(sourcefile, template=None, runas=None, options=None): ''' Uses the gzip command to create gzip files template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.gzip template=jinja /tmp/{{grains.id}}.txt runas : None The user with which to run the gzip command line options : None Pass any additional arguments to gzip .. versionadded:: 2016.3.4 CLI Example: .. code-block:: bash # Create /tmp/sourcefile.txt.gz salt '*' archive.gzip /tmp/sourcefile.txt salt '*' archive.gzip /tmp/sourcefile.txt options='-9 --verbose' ''' cmd = ['gzip'] if options: cmd.append(options) cmd.append('{0}'.format(sourcefile)) return __salt__['cmd.run'](cmd, template=template, runas=runas, python_shell=False).splitlines()
[ "def", "gzip", "(", "sourcefile", ",", "template", "=", "None", ",", "runas", "=", "None", ",", "options", "=", "None", ")", ":", "cmd", "=", "[", "'gzip'", "]", "if", "options", ":", "cmd", ".", "append", "(", "options", ")", "cmd", ".", "append",...
Uses the gzip command to create gzip files template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.gzip template=jinja /tmp/{{grains.id}}.txt runas : None The user with which to run the gzip command line options : None Pass any additional arguments to gzip .. versionadded:: 2016.3.4 CLI Example: .. code-block:: bash # Create /tmp/sourcefile.txt.gz salt '*' archive.gzip /tmp/sourcefile.txt salt '*' archive.gzip /tmp/sourcefile.txt options='-9 --verbose'
[ "Uses", "the", "gzip", "command", "to", "create", "gzip", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L554-L590
train
saltstack/salt
salt/modules/archive.py
gunzip
def gunzip(gzipfile, template=None, runas=None, options=None): ''' Uses the gunzip command to unpack gzip files template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.gunzip template=jinja /tmp/{{grains.id}}.txt.gz runas : None The user with which to run the gzip command line options : None Pass any additional arguments to gzip .. versionadded:: 2016.3.4 CLI Example: .. code-block:: bash # Create /tmp/sourcefile.txt salt '*' archive.gunzip /tmp/sourcefile.txt.gz salt '*' archive.gunzip /tmp/sourcefile.txt options='--verbose' ''' cmd = ['gunzip'] if options: cmd.append(options) cmd.append('{0}'.format(gzipfile)) return __salt__['cmd.run'](cmd, template=template, runas=runas, python_shell=False).splitlines()
python
def gunzip(gzipfile, template=None, runas=None, options=None): ''' Uses the gunzip command to unpack gzip files template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.gunzip template=jinja /tmp/{{grains.id}}.txt.gz runas : None The user with which to run the gzip command line options : None Pass any additional arguments to gzip .. versionadded:: 2016.3.4 CLI Example: .. code-block:: bash # Create /tmp/sourcefile.txt salt '*' archive.gunzip /tmp/sourcefile.txt.gz salt '*' archive.gunzip /tmp/sourcefile.txt options='--verbose' ''' cmd = ['gunzip'] if options: cmd.append(options) cmd.append('{0}'.format(gzipfile)) return __salt__['cmd.run'](cmd, template=template, runas=runas, python_shell=False).splitlines()
[ "def", "gunzip", "(", "gzipfile", ",", "template", "=", "None", ",", "runas", "=", "None", ",", "options", "=", "None", ")", ":", "cmd", "=", "[", "'gunzip'", "]", "if", "options", ":", "cmd", ".", "append", "(", "options", ")", "cmd", ".", "append...
Uses the gunzip command to unpack gzip files template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.gunzip template=jinja /tmp/{{grains.id}}.txt.gz runas : None The user with which to run the gzip command line options : None Pass any additional arguments to gzip .. versionadded:: 2016.3.4 CLI Example: .. code-block:: bash # Create /tmp/sourcefile.txt salt '*' archive.gunzip /tmp/sourcefile.txt.gz salt '*' archive.gunzip /tmp/sourcefile.txt options='--verbose'
[ "Uses", "the", "gunzip", "command", "to", "unpack", "gzip", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L594-L630
train
saltstack/salt
salt/modules/archive.py
cmd_zip
def cmd_zip(zip_file, sources, template=None, cwd=None, runas=None): ''' .. versionadded:: 2015.5.0 In versions 2014.7.x and earlier, this function was known as ``archive.zip``. Uses the ``zip`` command to create zip files. This command is part of the `Info-ZIP`_ suite of tools, and is typically packaged as simply ``zip``. .. _`Info-ZIP`: http://www.info-zip.org/ zip_file Path of zip file to be created sources Comma-separated list of sources to include in the zip file. Sources can also be passed in a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.cmd_zip template=jinja /tmp/zipfile.zip /tmp/sourcefile1,/tmp/{{grains.id}}.txt cwd : None Use this argument along with relative paths in ``sources`` to create zip files which do not contain the leading directories. If not specified, the zip file will be created as if the cwd was ``/``, and creating a zip file of ``/foo/bar/baz.txt`` will contain the parent directories ``foo`` and ``bar``. To create a zip file containing just ``baz.txt``, the following command would be used: .. code-block:: bash salt '*' archive.cmd_zip /tmp/baz.zip baz.txt cwd=/foo/bar .. versionadded:: 2014.7.1 runas : None Create the zip file as the specified user. Defaults to the user under which the minion is running. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' archive.cmd_zip /tmp/zipfile.zip /tmp/sourcefile1,/tmp/sourcefile2 # Globbing for sources (2017.7.0 and later) salt '*' archive.cmd_zip /tmp/zipfile.zip '/tmp/sourcefile*' ''' cmd = ['zip', '-r'] cmd.append('{0}'.format(zip_file)) cmd.extend(_expand_sources(sources)) return __salt__['cmd.run'](cmd, cwd=cwd, template=template, runas=runas, python_shell=False).splitlines()
python
def cmd_zip(zip_file, sources, template=None, cwd=None, runas=None): ''' .. versionadded:: 2015.5.0 In versions 2014.7.x and earlier, this function was known as ``archive.zip``. Uses the ``zip`` command to create zip files. This command is part of the `Info-ZIP`_ suite of tools, and is typically packaged as simply ``zip``. .. _`Info-ZIP`: http://www.info-zip.org/ zip_file Path of zip file to be created sources Comma-separated list of sources to include in the zip file. Sources can also be passed in a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.cmd_zip template=jinja /tmp/zipfile.zip /tmp/sourcefile1,/tmp/{{grains.id}}.txt cwd : None Use this argument along with relative paths in ``sources`` to create zip files which do not contain the leading directories. If not specified, the zip file will be created as if the cwd was ``/``, and creating a zip file of ``/foo/bar/baz.txt`` will contain the parent directories ``foo`` and ``bar``. To create a zip file containing just ``baz.txt``, the following command would be used: .. code-block:: bash salt '*' archive.cmd_zip /tmp/baz.zip baz.txt cwd=/foo/bar .. versionadded:: 2014.7.1 runas : None Create the zip file as the specified user. Defaults to the user under which the minion is running. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' archive.cmd_zip /tmp/zipfile.zip /tmp/sourcefile1,/tmp/sourcefile2 # Globbing for sources (2017.7.0 and later) salt '*' archive.cmd_zip /tmp/zipfile.zip '/tmp/sourcefile*' ''' cmd = ['zip', '-r'] cmd.append('{0}'.format(zip_file)) cmd.extend(_expand_sources(sources)) return __salt__['cmd.run'](cmd, cwd=cwd, template=template, runas=runas, python_shell=False).splitlines()
[ "def", "cmd_zip", "(", "zip_file", ",", "sources", ",", "template", "=", "None", ",", "cwd", "=", "None", ",", "runas", "=", "None", ")", ":", "cmd", "=", "[", "'zip'", ",", "'-r'", "]", "cmd", ".", "append", "(", "'{0}'", ".", "format", "(", "zi...
.. versionadded:: 2015.5.0 In versions 2014.7.x and earlier, this function was known as ``archive.zip``. Uses the ``zip`` command to create zip files. This command is part of the `Info-ZIP`_ suite of tools, and is typically packaged as simply ``zip``. .. _`Info-ZIP`: http://www.info-zip.org/ zip_file Path of zip file to be created sources Comma-separated list of sources to include in the zip file. Sources can also be passed in a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.cmd_zip template=jinja /tmp/zipfile.zip /tmp/sourcefile1,/tmp/{{grains.id}}.txt cwd : None Use this argument along with relative paths in ``sources`` to create zip files which do not contain the leading directories. If not specified, the zip file will be created as if the cwd was ``/``, and creating a zip file of ``/foo/bar/baz.txt`` will contain the parent directories ``foo`` and ``bar``. To create a zip file containing just ``baz.txt``, the following command would be used: .. code-block:: bash salt '*' archive.cmd_zip /tmp/baz.zip baz.txt cwd=/foo/bar .. versionadded:: 2014.7.1 runas : None Create the zip file as the specified user. Defaults to the user under which the minion is running. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' archive.cmd_zip /tmp/zipfile.zip /tmp/sourcefile1,/tmp/sourcefile2 # Globbing for sources (2017.7.0 and later) salt '*' archive.cmd_zip /tmp/zipfile.zip '/tmp/sourcefile*'
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0", "In", "versions", "2014", ".", "7", ".", "x", "and", "earlier", "this", "function", "was", "known", "as", "archive", ".", "zip", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L634-L699
train
saltstack/salt
salt/modules/archive.py
zip_
def zip_(zip_file, sources, template=None, cwd=None, runas=None, zip64=False): ''' Uses the ``zipfile`` Python module to create zip files .. versionchanged:: 2015.5.0 This function was rewritten to use Python's native zip file support. The old functionality has been preserved in the new function :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>`. For versions 2014.7.x and earlier, see the :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>` documentation. zip_file Path of zip file to be created sources Comma-separated list of sources to include in the zip file. Sources can also be passed in a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.zip template=jinja /tmp/zipfile.zip /tmp/sourcefile1,/tmp/{{grains.id}}.txt cwd : None Use this argument along with relative paths in ``sources`` to create zip files which do not contain the leading directories. If not specified, the zip file will be created as if the cwd was ``/``, and creating a zip file of ``/foo/bar/baz.txt`` will contain the parent directories ``foo`` and ``bar``. To create a zip file containing just ``baz.txt``, the following command would be used: .. code-block:: bash salt '*' archive.zip /tmp/baz.zip baz.txt cwd=/foo/bar runas : None Create the zip file as the specified user. Defaults to the user under which the minion is running. zip64 : False Used to enable ZIP64 support, necessary to create archives larger than 4 GByte in size. If true, will create ZIP file with the ZIPp64 extension when the zipfile is larger than 2 GB. ZIP64 extension is disabled by default in the Python native zip support because the default zip and unzip commands on Unix (the InfoZIP utilities) don't support these extensions. CLI Example: .. code-block:: bash salt '*' archive.zip /tmp/zipfile.zip /tmp/sourcefile1,/tmp/sourcefile2 # Globbing for sources (2017.7.0 and later) salt '*' archive.zip /tmp/zipfile.zip '/tmp/sourcefile*' ''' if runas: euid = os.geteuid() egid = os.getegid() uinfo = __salt__['user.info'](runas) if not uinfo: raise SaltInvocationError( 'User \'{0}\' does not exist'.format(runas) ) zip_file, sources = _render_filenames(zip_file, sources, None, template) sources = _expand_sources(sources) if not cwd: for src in sources: if not os.path.isabs(src): raise SaltInvocationError( 'Relative paths require the \'cwd\' parameter' ) else: err_msg = 'cwd must be absolute' try: if not os.path.isabs(cwd): raise SaltInvocationError(err_msg) except AttributeError: raise SaltInvocationError(err_msg) if runas and (euid != uinfo['uid'] or egid != uinfo['gid']): # Change the egid first, as changing it after the euid will fail # if the runas user is non-privileged. os.setegid(uinfo['gid']) os.seteuid(uinfo['uid']) try: exc = None archived_files = [] with contextlib.closing(zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED, zip64)) as zfile: for src in sources: if cwd: src = os.path.join(cwd, src) if os.path.exists(src): if os.path.isabs(src): rel_root = '/' else: rel_root = cwd if cwd is not None else '/' if os.path.isdir(src): for dir_name, sub_dirs, files in salt.utils.path.os_walk(src): if cwd and dir_name.startswith(cwd): arc_dir = os.path.relpath(dir_name, cwd) else: arc_dir = os.path.relpath(dir_name, rel_root) if arc_dir: archived_files.append(arc_dir + '/') zfile.write(dir_name, arc_dir) for filename in files: abs_name = os.path.join(dir_name, filename) arc_name = os.path.join(arc_dir, filename) archived_files.append(arc_name) zfile.write(abs_name, arc_name) else: if cwd and src.startswith(cwd): arc_name = os.path.relpath(src, cwd) else: arc_name = os.path.relpath(src, rel_root) archived_files.append(arc_name) zfile.write(src, arc_name) except Exception as exc: pass finally: # Restore the euid/egid if runas: os.seteuid(euid) os.setegid(egid) if exc is not None: # Wait to raise the exception until euid/egid are restored to avoid # permission errors in writing to minion log. if exc == zipfile.LargeZipFile: raise CommandExecutionError( 'Resulting zip file too large, would require ZIP64 support' 'which has not been enabled. Rerun command with zip64=True' ) else: raise CommandExecutionError( 'Exception encountered creating zipfile: {0}'.format(exc) ) return archived_files
python
def zip_(zip_file, sources, template=None, cwd=None, runas=None, zip64=False): ''' Uses the ``zipfile`` Python module to create zip files .. versionchanged:: 2015.5.0 This function was rewritten to use Python's native zip file support. The old functionality has been preserved in the new function :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>`. For versions 2014.7.x and earlier, see the :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>` documentation. zip_file Path of zip file to be created sources Comma-separated list of sources to include in the zip file. Sources can also be passed in a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.zip template=jinja /tmp/zipfile.zip /tmp/sourcefile1,/tmp/{{grains.id}}.txt cwd : None Use this argument along with relative paths in ``sources`` to create zip files which do not contain the leading directories. If not specified, the zip file will be created as if the cwd was ``/``, and creating a zip file of ``/foo/bar/baz.txt`` will contain the parent directories ``foo`` and ``bar``. To create a zip file containing just ``baz.txt``, the following command would be used: .. code-block:: bash salt '*' archive.zip /tmp/baz.zip baz.txt cwd=/foo/bar runas : None Create the zip file as the specified user. Defaults to the user under which the minion is running. zip64 : False Used to enable ZIP64 support, necessary to create archives larger than 4 GByte in size. If true, will create ZIP file with the ZIPp64 extension when the zipfile is larger than 2 GB. ZIP64 extension is disabled by default in the Python native zip support because the default zip and unzip commands on Unix (the InfoZIP utilities) don't support these extensions. CLI Example: .. code-block:: bash salt '*' archive.zip /tmp/zipfile.zip /tmp/sourcefile1,/tmp/sourcefile2 # Globbing for sources (2017.7.0 and later) salt '*' archive.zip /tmp/zipfile.zip '/tmp/sourcefile*' ''' if runas: euid = os.geteuid() egid = os.getegid() uinfo = __salt__['user.info'](runas) if not uinfo: raise SaltInvocationError( 'User \'{0}\' does not exist'.format(runas) ) zip_file, sources = _render_filenames(zip_file, sources, None, template) sources = _expand_sources(sources) if not cwd: for src in sources: if not os.path.isabs(src): raise SaltInvocationError( 'Relative paths require the \'cwd\' parameter' ) else: err_msg = 'cwd must be absolute' try: if not os.path.isabs(cwd): raise SaltInvocationError(err_msg) except AttributeError: raise SaltInvocationError(err_msg) if runas and (euid != uinfo['uid'] or egid != uinfo['gid']): # Change the egid first, as changing it after the euid will fail # if the runas user is non-privileged. os.setegid(uinfo['gid']) os.seteuid(uinfo['uid']) try: exc = None archived_files = [] with contextlib.closing(zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED, zip64)) as zfile: for src in sources: if cwd: src = os.path.join(cwd, src) if os.path.exists(src): if os.path.isabs(src): rel_root = '/' else: rel_root = cwd if cwd is not None else '/' if os.path.isdir(src): for dir_name, sub_dirs, files in salt.utils.path.os_walk(src): if cwd and dir_name.startswith(cwd): arc_dir = os.path.relpath(dir_name, cwd) else: arc_dir = os.path.relpath(dir_name, rel_root) if arc_dir: archived_files.append(arc_dir + '/') zfile.write(dir_name, arc_dir) for filename in files: abs_name = os.path.join(dir_name, filename) arc_name = os.path.join(arc_dir, filename) archived_files.append(arc_name) zfile.write(abs_name, arc_name) else: if cwd and src.startswith(cwd): arc_name = os.path.relpath(src, cwd) else: arc_name = os.path.relpath(src, rel_root) archived_files.append(arc_name) zfile.write(src, arc_name) except Exception as exc: pass finally: # Restore the euid/egid if runas: os.seteuid(euid) os.setegid(egid) if exc is not None: # Wait to raise the exception until euid/egid are restored to avoid # permission errors in writing to minion log. if exc == zipfile.LargeZipFile: raise CommandExecutionError( 'Resulting zip file too large, would require ZIP64 support' 'which has not been enabled. Rerun command with zip64=True' ) else: raise CommandExecutionError( 'Exception encountered creating zipfile: {0}'.format(exc) ) return archived_files
[ "def", "zip_", "(", "zip_file", ",", "sources", ",", "template", "=", "None", ",", "cwd", "=", "None", ",", "runas", "=", "None", ",", "zip64", "=", "False", ")", ":", "if", "runas", ":", "euid", "=", "os", ".", "geteuid", "(", ")", "egid", "=", ...
Uses the ``zipfile`` Python module to create zip files .. versionchanged:: 2015.5.0 This function was rewritten to use Python's native zip file support. The old functionality has been preserved in the new function :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>`. For versions 2014.7.x and earlier, see the :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>` documentation. zip_file Path of zip file to be created sources Comma-separated list of sources to include in the zip file. Sources can also be passed in a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.zip template=jinja /tmp/zipfile.zip /tmp/sourcefile1,/tmp/{{grains.id}}.txt cwd : None Use this argument along with relative paths in ``sources`` to create zip files which do not contain the leading directories. If not specified, the zip file will be created as if the cwd was ``/``, and creating a zip file of ``/foo/bar/baz.txt`` will contain the parent directories ``foo`` and ``bar``. To create a zip file containing just ``baz.txt``, the following command would be used: .. code-block:: bash salt '*' archive.zip /tmp/baz.zip baz.txt cwd=/foo/bar runas : None Create the zip file as the specified user. Defaults to the user under which the minion is running. zip64 : False Used to enable ZIP64 support, necessary to create archives larger than 4 GByte in size. If true, will create ZIP file with the ZIPp64 extension when the zipfile is larger than 2 GB. ZIP64 extension is disabled by default in the Python native zip support because the default zip and unzip commands on Unix (the InfoZIP utilities) don't support these extensions. CLI Example: .. code-block:: bash salt '*' archive.zip /tmp/zipfile.zip /tmp/sourcefile1,/tmp/sourcefile2 # Globbing for sources (2017.7.0 and later) salt '*' archive.zip /tmp/zipfile.zip '/tmp/sourcefile*'
[ "Uses", "the", "zipfile", "Python", "module", "to", "create", "zip", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L703-L850
train
saltstack/salt
salt/modules/archive.py
cmd_unzip
def cmd_unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None): ''' .. versionadded:: 2015.5.0 In versions 2014.7.x and earlier, this function was known as ``archive.unzip``. Uses the ``unzip`` command to unpack zip files. This command is part of the `Info-ZIP`_ suite of tools, and is typically packaged as simply ``unzip``. .. _`Info-ZIP`: http://www.info-zip.org/ zip_file Path of zip file to be unpacked dest The destination directory into which the file should be unpacked excludes : None Comma-separated list of files not to unpack. Can also be passed in a Python list. template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.cmd_unzip template=jinja /tmp/zipfile.zip '/tmp/{{grains.id}}' excludes=file_1,file_2 options Optional when using ``zip`` archives, ignored when usign other archives files. This is mostly used to overwrite existing files with ``o``. This options are only used when ``unzip`` binary is used. .. versionadded:: 2016.3.1 runas : None Unpack the zip file as the specified user. Defaults to the user under which the minion is running. .. versionadded:: 2015.5.0 trim_output : False The number of files we should output on success before the rest are trimmed, if this is set to True then it will default to 100 password Password to use with password protected zip files .. note:: This is not considered secure. It is recommended to instead use :py:func:`archive.unzip <salt.modules.archive.unzip>` for password-protected ZIP files. If a password is used here, then the unzip command run to extract the ZIP file will not show up in the minion log like most shell commands Salt runs do. However, the password will still be present in the events logged to the minion log at the ``debug`` log level. If the minion is logging at ``debug`` (or more verbose), then be advised that the password will appear in the log. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' archive.cmd_unzip /tmp/zipfile.zip /home/strongbad/ excludes=file_1,file_2 ''' if isinstance(excludes, six.string_types): excludes = [x.strip() for x in excludes.split(',')] elif isinstance(excludes, (float, six.integer_types)): excludes = [six.text_type(excludes)] cmd = ['unzip'] if password: cmd.extend(['-P', password]) if options: cmd.extend(shlex.split(options)) cmd.extend(['{0}'.format(zip_file), '-d', '{0}'.format(dest)]) if excludes is not None: cmd.append('-x') cmd.extend(excludes) result = __salt__['cmd.run_all']( cmd, template=template, runas=runas, python_shell=False, redirect_stderr=True, output_loglevel='quiet' if password else 'debug') if result['retcode'] != 0: raise CommandExecutionError(result['stdout']) return _trim_files(result['stdout'].splitlines(), trim_output)
python
def cmd_unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None): ''' .. versionadded:: 2015.5.0 In versions 2014.7.x and earlier, this function was known as ``archive.unzip``. Uses the ``unzip`` command to unpack zip files. This command is part of the `Info-ZIP`_ suite of tools, and is typically packaged as simply ``unzip``. .. _`Info-ZIP`: http://www.info-zip.org/ zip_file Path of zip file to be unpacked dest The destination directory into which the file should be unpacked excludes : None Comma-separated list of files not to unpack. Can also be passed in a Python list. template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.cmd_unzip template=jinja /tmp/zipfile.zip '/tmp/{{grains.id}}' excludes=file_1,file_2 options Optional when using ``zip`` archives, ignored when usign other archives files. This is mostly used to overwrite existing files with ``o``. This options are only used when ``unzip`` binary is used. .. versionadded:: 2016.3.1 runas : None Unpack the zip file as the specified user. Defaults to the user under which the minion is running. .. versionadded:: 2015.5.0 trim_output : False The number of files we should output on success before the rest are trimmed, if this is set to True then it will default to 100 password Password to use with password protected zip files .. note:: This is not considered secure. It is recommended to instead use :py:func:`archive.unzip <salt.modules.archive.unzip>` for password-protected ZIP files. If a password is used here, then the unzip command run to extract the ZIP file will not show up in the minion log like most shell commands Salt runs do. However, the password will still be present in the events logged to the minion log at the ``debug`` log level. If the minion is logging at ``debug`` (or more verbose), then be advised that the password will appear in the log. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' archive.cmd_unzip /tmp/zipfile.zip /home/strongbad/ excludes=file_1,file_2 ''' if isinstance(excludes, six.string_types): excludes = [x.strip() for x in excludes.split(',')] elif isinstance(excludes, (float, six.integer_types)): excludes = [six.text_type(excludes)] cmd = ['unzip'] if password: cmd.extend(['-P', password]) if options: cmd.extend(shlex.split(options)) cmd.extend(['{0}'.format(zip_file), '-d', '{0}'.format(dest)]) if excludes is not None: cmd.append('-x') cmd.extend(excludes) result = __salt__['cmd.run_all']( cmd, template=template, runas=runas, python_shell=False, redirect_stderr=True, output_loglevel='quiet' if password else 'debug') if result['retcode'] != 0: raise CommandExecutionError(result['stdout']) return _trim_files(result['stdout'].splitlines(), trim_output)
[ "def", "cmd_unzip", "(", "zip_file", ",", "dest", ",", "excludes", "=", "None", ",", "options", "=", "None", ",", "template", "=", "None", ",", "runas", "=", "None", ",", "trim_output", "=", "False", ",", "password", "=", "None", ")", ":", "if", "isi...
.. versionadded:: 2015.5.0 In versions 2014.7.x and earlier, this function was known as ``archive.unzip``. Uses the ``unzip`` command to unpack zip files. This command is part of the `Info-ZIP`_ suite of tools, and is typically packaged as simply ``unzip``. .. _`Info-ZIP`: http://www.info-zip.org/ zip_file Path of zip file to be unpacked dest The destination directory into which the file should be unpacked excludes : None Comma-separated list of files not to unpack. Can also be passed in a Python list. template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.cmd_unzip template=jinja /tmp/zipfile.zip '/tmp/{{grains.id}}' excludes=file_1,file_2 options Optional when using ``zip`` archives, ignored when usign other archives files. This is mostly used to overwrite existing files with ``o``. This options are only used when ``unzip`` binary is used. .. versionadded:: 2016.3.1 runas : None Unpack the zip file as the specified user. Defaults to the user under which the minion is running. .. versionadded:: 2015.5.0 trim_output : False The number of files we should output on success before the rest are trimmed, if this is set to True then it will default to 100 password Password to use with password protected zip files .. note:: This is not considered secure. It is recommended to instead use :py:func:`archive.unzip <salt.modules.archive.unzip>` for password-protected ZIP files. If a password is used here, then the unzip command run to extract the ZIP file will not show up in the minion log like most shell commands Salt runs do. However, the password will still be present in the events logged to the minion log at the ``debug`` log level. If the minion is logging at ``debug`` (or more verbose), then be advised that the password will appear in the log. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' archive.cmd_unzip /tmp/zipfile.zip /home/strongbad/ excludes=file_1,file_2
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0", "In", "versions", "2014", ".", "7", ".", "x", "and", "earlier", "this", "function", "was", "known", "as", "archive", ".", "unzip", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L854-L957
train
saltstack/salt
salt/modules/archive.py
unzip
def unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None, extract_perms=True): ''' Uses the ``zipfile`` Python module to unpack zip files .. versionchanged:: 2015.5.0 This function was rewritten to use Python's native zip file support. The old functionality has been preserved in the new function :mod:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`. For versions 2014.7.x and earlier, see the :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>` documentation. zip_file Path of zip file to be unpacked dest The destination directory into which the file should be unpacked excludes : None Comma-separated list of files not to unpack. Can also be passed in a Python list. options This options are only used when ``unzip`` binary is used. In this function is ignored. .. versionadded:: 2016.3.1 template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.unzip template=jinja /tmp/zipfile.zip /tmp/{{grains.id}}/ excludes=file_1,file_2 runas : None Unpack the zip file as the specified user. Defaults to the user under which the minion is running. trim_output : False The number of files we should output on success before the rest are trimmed, if this is set to True then it will default to 100 CLI Example: .. code-block:: bash salt '*' archive.unzip /tmp/zipfile.zip /home/strongbad/ excludes=file_1,file_2 password Password to use with password protected zip files .. note:: The password will be present in the events logged to the minion log file at the ``debug`` log level. If the minion is logging at ``debug`` (or more verbose), then be advised that the password will appear in the log. .. versionadded:: 2016.3.0 extract_perms : True The Python zipfile_ module does not extract file/directory attributes by default. When this argument is set to ``True``, Salt will attempt to apply the file permission attributes to the extracted files/folders. On Windows, only the read-only flag will be extracted as set within the zip file, other attributes (i.e. user/group permissions) are ignored. Set this argument to ``False`` to disable this behavior. .. versionadded:: 2016.11.0 .. _zipfile: https://docs.python.org/2/library/zipfile.html CLI Example: .. code-block:: bash salt '*' archive.unzip /tmp/zipfile.zip /home/strongbad/ password='BadPassword' ''' if not excludes: excludes = [] if runas: euid = os.geteuid() egid = os.getegid() uinfo = __salt__['user.info'](runas) if not uinfo: raise SaltInvocationError( "User '{0}' does not exist".format(runas) ) zip_file, dest = _render_filenames(zip_file, dest, None, template) if runas and (euid != uinfo['uid'] or egid != uinfo['gid']): # Change the egid first, as changing it after the euid will fail # if the runas user is non-privileged. os.setegid(uinfo['gid']) os.seteuid(uinfo['uid']) try: # Define cleaned_files here so that an exception will not prevent this # variable from being defined and cause a NameError in the return # statement at the end of the function. cleaned_files = [] with contextlib.closing(zipfile.ZipFile(zip_file, "r")) as zfile: files = zfile.namelist() if isinstance(excludes, six.string_types): excludes = [x.strip() for x in excludes.split(',')] elif isinstance(excludes, (float, six.integer_types)): excludes = [six.text_type(excludes)] cleaned_files.extend([x for x in files if x not in excludes]) for target in cleaned_files: if target not in excludes: if salt.utils.platform.is_windows() is False: info = zfile.getinfo(target) # Check if zipped file is a symbolic link if stat.S_ISLNK(info.external_attr >> 16): source = zfile.read(target) os.symlink(source, os.path.join(dest, target)) continue zfile.extract(target, dest, password) if extract_perms: if not salt.utils.platform.is_windows(): perm = zfile.getinfo(target).external_attr >> 16 if perm == 0: umask_ = salt.utils.files.get_umask() if target.endswith('/'): perm = 0o777 & ~umask_ else: perm = 0o666 & ~umask_ os.chmod(os.path.join(dest, target), perm) else: win32_attr = zfile.getinfo(target).external_attr & 0xFF win32file.SetFileAttributes(os.path.join(dest, target), win32_attr) except Exception as exc: if runas: os.seteuid(euid) os.setegid(egid) # Wait to raise the exception until euid/egid are restored to avoid # permission errors in writing to minion log. raise CommandExecutionError( 'Exception encountered unpacking zipfile: {0}'.format(exc) ) finally: # Restore the euid/egid if runas: os.seteuid(euid) os.setegid(egid) return _trim_files(cleaned_files, trim_output)
python
def unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None, extract_perms=True): ''' Uses the ``zipfile`` Python module to unpack zip files .. versionchanged:: 2015.5.0 This function was rewritten to use Python's native zip file support. The old functionality has been preserved in the new function :mod:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`. For versions 2014.7.x and earlier, see the :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>` documentation. zip_file Path of zip file to be unpacked dest The destination directory into which the file should be unpacked excludes : None Comma-separated list of files not to unpack. Can also be passed in a Python list. options This options are only used when ``unzip`` binary is used. In this function is ignored. .. versionadded:: 2016.3.1 template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.unzip template=jinja /tmp/zipfile.zip /tmp/{{grains.id}}/ excludes=file_1,file_2 runas : None Unpack the zip file as the specified user. Defaults to the user under which the minion is running. trim_output : False The number of files we should output on success before the rest are trimmed, if this is set to True then it will default to 100 CLI Example: .. code-block:: bash salt '*' archive.unzip /tmp/zipfile.zip /home/strongbad/ excludes=file_1,file_2 password Password to use with password protected zip files .. note:: The password will be present in the events logged to the minion log file at the ``debug`` log level. If the minion is logging at ``debug`` (or more verbose), then be advised that the password will appear in the log. .. versionadded:: 2016.3.0 extract_perms : True The Python zipfile_ module does not extract file/directory attributes by default. When this argument is set to ``True``, Salt will attempt to apply the file permission attributes to the extracted files/folders. On Windows, only the read-only flag will be extracted as set within the zip file, other attributes (i.e. user/group permissions) are ignored. Set this argument to ``False`` to disable this behavior. .. versionadded:: 2016.11.0 .. _zipfile: https://docs.python.org/2/library/zipfile.html CLI Example: .. code-block:: bash salt '*' archive.unzip /tmp/zipfile.zip /home/strongbad/ password='BadPassword' ''' if not excludes: excludes = [] if runas: euid = os.geteuid() egid = os.getegid() uinfo = __salt__['user.info'](runas) if not uinfo: raise SaltInvocationError( "User '{0}' does not exist".format(runas) ) zip_file, dest = _render_filenames(zip_file, dest, None, template) if runas and (euid != uinfo['uid'] or egid != uinfo['gid']): # Change the egid first, as changing it after the euid will fail # if the runas user is non-privileged. os.setegid(uinfo['gid']) os.seteuid(uinfo['uid']) try: # Define cleaned_files here so that an exception will not prevent this # variable from being defined and cause a NameError in the return # statement at the end of the function. cleaned_files = [] with contextlib.closing(zipfile.ZipFile(zip_file, "r")) as zfile: files = zfile.namelist() if isinstance(excludes, six.string_types): excludes = [x.strip() for x in excludes.split(',')] elif isinstance(excludes, (float, six.integer_types)): excludes = [six.text_type(excludes)] cleaned_files.extend([x for x in files if x not in excludes]) for target in cleaned_files: if target not in excludes: if salt.utils.platform.is_windows() is False: info = zfile.getinfo(target) # Check if zipped file is a symbolic link if stat.S_ISLNK(info.external_attr >> 16): source = zfile.read(target) os.symlink(source, os.path.join(dest, target)) continue zfile.extract(target, dest, password) if extract_perms: if not salt.utils.platform.is_windows(): perm = zfile.getinfo(target).external_attr >> 16 if perm == 0: umask_ = salt.utils.files.get_umask() if target.endswith('/'): perm = 0o777 & ~umask_ else: perm = 0o666 & ~umask_ os.chmod(os.path.join(dest, target), perm) else: win32_attr = zfile.getinfo(target).external_attr & 0xFF win32file.SetFileAttributes(os.path.join(dest, target), win32_attr) except Exception as exc: if runas: os.seteuid(euid) os.setegid(egid) # Wait to raise the exception until euid/egid are restored to avoid # permission errors in writing to minion log. raise CommandExecutionError( 'Exception encountered unpacking zipfile: {0}'.format(exc) ) finally: # Restore the euid/egid if runas: os.seteuid(euid) os.setegid(egid) return _trim_files(cleaned_files, trim_output)
[ "def", "unzip", "(", "zip_file", ",", "dest", ",", "excludes", "=", "None", ",", "options", "=", "None", ",", "template", "=", "None", ",", "runas", "=", "None", ",", "trim_output", "=", "False", ",", "password", "=", "None", ",", "extract_perms", "=",...
Uses the ``zipfile`` Python module to unpack zip files .. versionchanged:: 2015.5.0 This function was rewritten to use Python's native zip file support. The old functionality has been preserved in the new function :mod:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`. For versions 2014.7.x and earlier, see the :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>` documentation. zip_file Path of zip file to be unpacked dest The destination directory into which the file should be unpacked excludes : None Comma-separated list of files not to unpack. Can also be passed in a Python list. options This options are only used when ``unzip`` binary is used. In this function is ignored. .. versionadded:: 2016.3.1 template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.unzip template=jinja /tmp/zipfile.zip /tmp/{{grains.id}}/ excludes=file_1,file_2 runas : None Unpack the zip file as the specified user. Defaults to the user under which the minion is running. trim_output : False The number of files we should output on success before the rest are trimmed, if this is set to True then it will default to 100 CLI Example: .. code-block:: bash salt '*' archive.unzip /tmp/zipfile.zip /home/strongbad/ excludes=file_1,file_2 password Password to use with password protected zip files .. note:: The password will be present in the events logged to the minion log file at the ``debug`` log level. If the minion is logging at ``debug`` (or more verbose), then be advised that the password will appear in the log. .. versionadded:: 2016.3.0 extract_perms : True The Python zipfile_ module does not extract file/directory attributes by default. When this argument is set to ``True``, Salt will attempt to apply the file permission attributes to the extracted files/folders. On Windows, only the read-only flag will be extracted as set within the zip file, other attributes (i.e. user/group permissions) are ignored. Set this argument to ``False`` to disable this behavior. .. versionadded:: 2016.11.0 .. _zipfile: https://docs.python.org/2/library/zipfile.html CLI Example: .. code-block:: bash salt '*' archive.unzip /tmp/zipfile.zip /home/strongbad/ password='BadPassword'
[ "Uses", "the", "zipfile", "Python", "module", "to", "unpack", "zip", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L960-L1119
train
saltstack/salt
salt/modules/archive.py
is_encrypted
def is_encrypted(name, clean=False, saltenv='base', source_hash=None): ''' .. versionadded:: 2016.11.0 Returns ``True`` if the zip archive is password-protected, ``False`` if not. If the specified file is not a ZIP archive, an error will be raised. name The path / URL of the archive to check. clean : False Set this value to ``True`` to delete the path referred to by ``name`` once the contents have been listed. This option should be used with care. .. note:: If there is an error listing the archive's contents, the cached file will not be removed, to allow for troubleshooting. saltenv : base Specifies the fileserver environment from which to retrieve ``archive``. This is only applicable when ``archive`` is a file from the ``salt://`` fileserver. source_hash If ``name`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' archive.is_encrypted /path/to/myfile.zip salt '*' archive.is_encrypted salt://foo.zip salt '*' archive.is_encrypted salt://foo.zip saltenv=dev salt '*' archive.is_encrypted https://domain.tld/myfile.zip clean=True salt '*' archive.is_encrypted https://domain.tld/myfile.zip source_hash=f1d2d2f924e986ac86fdf7b36c94bcdf32beec15 salt '*' archive.is_encrypted ftp://10.1.2.3/foo.zip ''' cached = __salt__['cp.cache_file'](name, saltenv, source_hash=source_hash) if not cached: raise CommandExecutionError('Failed to cache {0}'.format(name)) archive_info = {'archive location': cached} try: with contextlib.closing(zipfile.ZipFile(cached)) as zip_archive: zip_archive.testzip() except RuntimeError: ret = True except zipfile.BadZipfile: raise CommandExecutionError( '{0} is not a ZIP file'.format(name), info=archive_info ) except Exception as exc: raise CommandExecutionError(exc.__str__(), info=archive_info) else: ret = False if clean: try: os.remove(cached) log.debug('Cleaned cached archive %s', cached) except OSError as exc: if exc.errno != errno.ENOENT: log.warning( 'Failed to clean cached archive %s: %s', cached, exc.__str__() ) return ret
python
def is_encrypted(name, clean=False, saltenv='base', source_hash=None): ''' .. versionadded:: 2016.11.0 Returns ``True`` if the zip archive is password-protected, ``False`` if not. If the specified file is not a ZIP archive, an error will be raised. name The path / URL of the archive to check. clean : False Set this value to ``True`` to delete the path referred to by ``name`` once the contents have been listed. This option should be used with care. .. note:: If there is an error listing the archive's contents, the cached file will not be removed, to allow for troubleshooting. saltenv : base Specifies the fileserver environment from which to retrieve ``archive``. This is only applicable when ``archive`` is a file from the ``salt://`` fileserver. source_hash If ``name`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' archive.is_encrypted /path/to/myfile.zip salt '*' archive.is_encrypted salt://foo.zip salt '*' archive.is_encrypted salt://foo.zip saltenv=dev salt '*' archive.is_encrypted https://domain.tld/myfile.zip clean=True salt '*' archive.is_encrypted https://domain.tld/myfile.zip source_hash=f1d2d2f924e986ac86fdf7b36c94bcdf32beec15 salt '*' archive.is_encrypted ftp://10.1.2.3/foo.zip ''' cached = __salt__['cp.cache_file'](name, saltenv, source_hash=source_hash) if not cached: raise CommandExecutionError('Failed to cache {0}'.format(name)) archive_info = {'archive location': cached} try: with contextlib.closing(zipfile.ZipFile(cached)) as zip_archive: zip_archive.testzip() except RuntimeError: ret = True except zipfile.BadZipfile: raise CommandExecutionError( '{0} is not a ZIP file'.format(name), info=archive_info ) except Exception as exc: raise CommandExecutionError(exc.__str__(), info=archive_info) else: ret = False if clean: try: os.remove(cached) log.debug('Cleaned cached archive %s', cached) except OSError as exc: if exc.errno != errno.ENOENT: log.warning( 'Failed to clean cached archive %s: %s', cached, exc.__str__() ) return ret
[ "def", "is_encrypted", "(", "name", ",", "clean", "=", "False", ",", "saltenv", "=", "'base'", ",", "source_hash", "=", "None", ")", ":", "cached", "=", "__salt__", "[", "'cp.cache_file'", "]", "(", "name", ",", "saltenv", ",", "source_hash", "=", "sourc...
.. versionadded:: 2016.11.0 Returns ``True`` if the zip archive is password-protected, ``False`` if not. If the specified file is not a ZIP archive, an error will be raised. name The path / URL of the archive to check. clean : False Set this value to ``True`` to delete the path referred to by ``name`` once the contents have been listed. This option should be used with care. .. note:: If there is an error listing the archive's contents, the cached file will not be removed, to allow for troubleshooting. saltenv : base Specifies the fileserver environment from which to retrieve ``archive``. This is only applicable when ``archive`` is a file from the ``salt://`` fileserver. source_hash If ``name`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' archive.is_encrypted /path/to/myfile.zip salt '*' archive.is_encrypted salt://foo.zip salt '*' archive.is_encrypted salt://foo.zip saltenv=dev salt '*' archive.is_encrypted https://domain.tld/myfile.zip clean=True salt '*' archive.is_encrypted https://domain.tld/myfile.zip source_hash=f1d2d2f924e986ac86fdf7b36c94bcdf32beec15 salt '*' archive.is_encrypted ftp://10.1.2.3/foo.zip
[ "..", "versionadded", "::", "2016", ".", "11", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L1122-L1195
train
saltstack/salt
salt/modules/archive.py
rar
def rar(rarfile, sources, template=None, cwd=None, runas=None): ''' Uses `rar for Linux`_ to create rar files .. _`rar for Linux`: http://www.rarlab.com/ rarfile Path of rar file to be created sources Comma-separated list of sources to include in the rar file. Sources can also be passed in a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument cwd : None Run the rar command from the specified directory. Use this argument along with relative file paths to create rar files which do not contain the leading directories. If not specified, this will default to the home directory of the user under which the salt minion process is running. .. versionadded:: 2014.7.1 template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.rar template=jinja /tmp/rarfile.rar '/tmp/sourcefile1,/tmp/{{grains.id}}.txt' CLI Example: .. code-block:: bash salt '*' archive.rar /tmp/rarfile.rar /tmp/sourcefile1,/tmp/sourcefile2 # Globbing for sources (2017.7.0 and later) salt '*' archive.rar /tmp/rarfile.rar '/tmp/sourcefile*' ''' cmd = ['rar', 'a', '-idp', '{0}'.format(rarfile)] cmd.extend(_expand_sources(sources)) return __salt__['cmd.run'](cmd, cwd=cwd, template=template, runas=runas, python_shell=False).splitlines()
python
def rar(rarfile, sources, template=None, cwd=None, runas=None): ''' Uses `rar for Linux`_ to create rar files .. _`rar for Linux`: http://www.rarlab.com/ rarfile Path of rar file to be created sources Comma-separated list of sources to include in the rar file. Sources can also be passed in a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument cwd : None Run the rar command from the specified directory. Use this argument along with relative file paths to create rar files which do not contain the leading directories. If not specified, this will default to the home directory of the user under which the salt minion process is running. .. versionadded:: 2014.7.1 template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.rar template=jinja /tmp/rarfile.rar '/tmp/sourcefile1,/tmp/{{grains.id}}.txt' CLI Example: .. code-block:: bash salt '*' archive.rar /tmp/rarfile.rar /tmp/sourcefile1,/tmp/sourcefile2 # Globbing for sources (2017.7.0 and later) salt '*' archive.rar /tmp/rarfile.rar '/tmp/sourcefile*' ''' cmd = ['rar', 'a', '-idp', '{0}'.format(rarfile)] cmd.extend(_expand_sources(sources)) return __salt__['cmd.run'](cmd, cwd=cwd, template=template, runas=runas, python_shell=False).splitlines()
[ "def", "rar", "(", "rarfile", ",", "sources", ",", "template", "=", "None", ",", "cwd", "=", "None", ",", "runas", "=", "None", ")", ":", "cmd", "=", "[", "'rar'", ",", "'a'", ",", "'-idp'", ",", "'{0}'", ".", "format", "(", "rarfile", ")", "]", ...
Uses `rar for Linux`_ to create rar files .. _`rar for Linux`: http://www.rarlab.com/ rarfile Path of rar file to be created sources Comma-separated list of sources to include in the rar file. Sources can also be passed in a Python list. .. versionchanged:: 2017.7.0 Globbing is now supported for this argument cwd : None Run the rar command from the specified directory. Use this argument along with relative file paths to create rar files which do not contain the leading directories. If not specified, this will default to the home directory of the user under which the salt minion process is running. .. versionadded:: 2014.7.1 template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.rar template=jinja /tmp/rarfile.rar '/tmp/sourcefile1,/tmp/{{grains.id}}.txt' CLI Example: .. code-block:: bash salt '*' archive.rar /tmp/rarfile.rar /tmp/sourcefile1,/tmp/sourcefile2 # Globbing for sources (2017.7.0 and later) salt '*' archive.rar /tmp/rarfile.rar '/tmp/sourcefile*'
[ "Uses", "rar", "for", "Linux", "_", "to", "create", "rar", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L1199-L1246
train
saltstack/salt
salt/modules/archive.py
unrar
def unrar(rarfile, dest, excludes=None, template=None, runas=None, trim_output=False): ''' Uses `rar for Linux`_ to unpack rar files .. _`rar for Linux`: http://www.rarlab.com/ rarfile Name of rar file to be unpacked dest The destination directory into which to **unpack** the rar file template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.unrar template=jinja /tmp/rarfile.rar /tmp/{{grains.id}}/ excludes=file_1,file_2 trim_output : False The number of files we should output on success before the rest are trimmed, if this is set to True then it will default to 100 CLI Example: .. code-block:: bash salt '*' archive.unrar /tmp/rarfile.rar /home/strongbad/ excludes=file_1,file_2 ''' if isinstance(excludes, six.string_types): excludes = [entry.strip() for entry in excludes.split(',')] cmd = [salt.utils.path.which_bin(('unrar', 'rar')), 'x', '-idp', '{0}'.format(rarfile)] if excludes is not None: for exclude in excludes: cmd.extend(['-x', '{0}'.format(exclude)]) cmd.append('{0}'.format(dest)) files = __salt__['cmd.run'](cmd, template=template, runas=runas, python_shell=False).splitlines() return _trim_files(files, trim_output)
python
def unrar(rarfile, dest, excludes=None, template=None, runas=None, trim_output=False): ''' Uses `rar for Linux`_ to unpack rar files .. _`rar for Linux`: http://www.rarlab.com/ rarfile Name of rar file to be unpacked dest The destination directory into which to **unpack** the rar file template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.unrar template=jinja /tmp/rarfile.rar /tmp/{{grains.id}}/ excludes=file_1,file_2 trim_output : False The number of files we should output on success before the rest are trimmed, if this is set to True then it will default to 100 CLI Example: .. code-block:: bash salt '*' archive.unrar /tmp/rarfile.rar /home/strongbad/ excludes=file_1,file_2 ''' if isinstance(excludes, six.string_types): excludes = [entry.strip() for entry in excludes.split(',')] cmd = [salt.utils.path.which_bin(('unrar', 'rar')), 'x', '-idp', '{0}'.format(rarfile)] if excludes is not None: for exclude in excludes: cmd.extend(['-x', '{0}'.format(exclude)]) cmd.append('{0}'.format(dest)) files = __salt__['cmd.run'](cmd, template=template, runas=runas, python_shell=False).splitlines() return _trim_files(files, trim_output)
[ "def", "unrar", "(", "rarfile", ",", "dest", ",", "excludes", "=", "None", ",", "template", "=", "None", ",", "runas", "=", "None", ",", "trim_output", "=", "False", ")", ":", "if", "isinstance", "(", "excludes", ",", "six", ".", "string_types", ")", ...
Uses `rar for Linux`_ to unpack rar files .. _`rar for Linux`: http://www.rarlab.com/ rarfile Name of rar file to be unpacked dest The destination directory into which to **unpack** the rar file template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.unrar template=jinja /tmp/rarfile.rar /tmp/{{grains.id}}/ excludes=file_1,file_2 trim_output : False The number of files we should output on success before the rest are trimmed, if this is set to True then it will default to 100 CLI Example: .. code-block:: bash salt '*' archive.unrar /tmp/rarfile.rar /home/strongbad/ excludes=file_1,file_2
[ "Uses", "rar", "for", "Linux", "_", "to", "unpack", "rar", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L1250-L1295
train
saltstack/salt
salt/modules/archive.py
_render_filenames
def _render_filenames(filenames, zip_file, saltenv, template): ''' Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the files under the paths they ultimately point to) according to the markup format provided by :param:`template`. ''' if not template: return (filenames, zip_file) # render the path as a template using path_template_engine as the engine if template not in salt.utils.templates.TEMPLATE_REGISTRY: raise CommandExecutionError( 'Attempted to render file paths with unavailable engine ' '{0}'.format(template) ) kwargs = {} kwargs['salt'] = __salt__ kwargs['pillar'] = __pillar__ kwargs['grains'] = __grains__ kwargs['opts'] = __opts__ kwargs['saltenv'] = saltenv def _render(contents): ''' Render :param:`contents` into a literal pathname by writing it to a temp file, rendering that file, and returning the result. ''' # write out path to temp file tmp_path_fn = salt.utils.files.mkstemp() with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_: fp_.write(salt.utils.stringutils.to_str(contents)) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( tmp_path_fn, to_str=True, **kwargs ) salt.utils.files.safe_rm(tmp_path_fn) if not data['result']: # Failed to render the template raise CommandExecutionError( 'Failed to render file path with error: {0}'.format( data['data'] ) ) else: return data['data'] filenames = _render(filenames) zip_file = _render(zip_file) return (filenames, zip_file)
python
def _render_filenames(filenames, zip_file, saltenv, template): ''' Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the files under the paths they ultimately point to) according to the markup format provided by :param:`template`. ''' if not template: return (filenames, zip_file) # render the path as a template using path_template_engine as the engine if template not in salt.utils.templates.TEMPLATE_REGISTRY: raise CommandExecutionError( 'Attempted to render file paths with unavailable engine ' '{0}'.format(template) ) kwargs = {} kwargs['salt'] = __salt__ kwargs['pillar'] = __pillar__ kwargs['grains'] = __grains__ kwargs['opts'] = __opts__ kwargs['saltenv'] = saltenv def _render(contents): ''' Render :param:`contents` into a literal pathname by writing it to a temp file, rendering that file, and returning the result. ''' # write out path to temp file tmp_path_fn = salt.utils.files.mkstemp() with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_: fp_.write(salt.utils.stringutils.to_str(contents)) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( tmp_path_fn, to_str=True, **kwargs ) salt.utils.files.safe_rm(tmp_path_fn) if not data['result']: # Failed to render the template raise CommandExecutionError( 'Failed to render file path with error: {0}'.format( data['data'] ) ) else: return data['data'] filenames = _render(filenames) zip_file = _render(zip_file) return (filenames, zip_file)
[ "def", "_render_filenames", "(", "filenames", ",", "zip_file", ",", "saltenv", ",", "template", ")", ":", "if", "not", "template", ":", "return", "(", "filenames", ",", "zip_file", ")", "# render the path as a template using path_template_engine as the engine", "if", ...
Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the files under the paths they ultimately point to) according to the markup format provided by :param:`template`.
[ "Process", "markup", "in", "the", ":", "param", ":", "filenames", "and", ":", "param", ":", "zipfile", "variables", "(", "NOT", "the", "files", "under", "the", "paths", "they", "ultimately", "point", "to", ")", "according", "to", "the", "markup", "format",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L1298-L1348
train
saltstack/salt
salt/modules/archive.py
_trim_files
def _trim_files(files, trim_output): ''' Trim the file list for output. ''' count = 100 if not isinstance(trim_output, bool): count = trim_output if not(isinstance(trim_output, bool) and trim_output is False) and len(files) > count: files = files[:count] files.append("List trimmed after {0} files.".format(count)) return files
python
def _trim_files(files, trim_output): ''' Trim the file list for output. ''' count = 100 if not isinstance(trim_output, bool): count = trim_output if not(isinstance(trim_output, bool) and trim_output is False) and len(files) > count: files = files[:count] files.append("List trimmed after {0} files.".format(count)) return files
[ "def", "_trim_files", "(", "files", ",", "trim_output", ")", ":", "count", "=", "100", "if", "not", "isinstance", "(", "trim_output", ",", "bool", ")", ":", "count", "=", "trim_output", "if", "not", "(", "isinstance", "(", "trim_output", ",", "bool", ")"...
Trim the file list for output.
[ "Trim", "the", "file", "list", "for", "output", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L1351-L1363
train
saltstack/salt
salt/pillar/nsot.py
_get_token
def _get_token(url, email, secret_key): ''' retrieve the auth_token from nsot :param url: str :param email: str :param secret_key: str :return: str ''' url = urlparse.urljoin(url, 'authenticate') data_dict = {"email": email, "secret_key": secret_key} query = salt.utils.http.query(url, data=data_dict, method='POST', decode=True) error = query.get('error') if error: log.error('Cannot obtain NSoT authentication token due to: %s.', error) log.debug('Please verify NSoT URL %s is reachable and email %s is valid', url, email) return False else: log.debug('successfully obtained token from nsot!') return query['dict'].get('auth_token')
python
def _get_token(url, email, secret_key): ''' retrieve the auth_token from nsot :param url: str :param email: str :param secret_key: str :return: str ''' url = urlparse.urljoin(url, 'authenticate') data_dict = {"email": email, "secret_key": secret_key} query = salt.utils.http.query(url, data=data_dict, method='POST', decode=True) error = query.get('error') if error: log.error('Cannot obtain NSoT authentication token due to: %s.', error) log.debug('Please verify NSoT URL %s is reachable and email %s is valid', url, email) return False else: log.debug('successfully obtained token from nsot!') return query['dict'].get('auth_token')
[ "def", "_get_token", "(", "url", ",", "email", ",", "secret_key", ")", ":", "url", "=", "urlparse", ".", "urljoin", "(", "url", ",", "'authenticate'", ")", "data_dict", "=", "{", "\"email\"", ":", "email", ",", "\"secret_key\"", ":", "secret_key", "}", "...
retrieve the auth_token from nsot :param url: str :param email: str :param secret_key: str :return: str
[ "retrieve", "the", "auth_token", "from", "nsot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/nsot.py#L80-L100
train
saltstack/salt
salt/pillar/nsot.py
_check_regex
def _check_regex(minion_id, regex): ''' check whether or not this minion should have this external pillar returned :param minion_id: str :param minion_regex: list :return: bool ''' get_pillar = False for pattern in regex: log.debug('nsot external pillar comparing %s with %s', minion_id, regex) match = re.search(pattern, minion_id) if match and match.string == minion_id: log.debug('nsot external pillar found a match!') get_pillar = True break log.debug('nsot external pillar unable to find a match!') return get_pillar
python
def _check_regex(minion_id, regex): ''' check whether or not this minion should have this external pillar returned :param minion_id: str :param minion_regex: list :return: bool ''' get_pillar = False for pattern in regex: log.debug('nsot external pillar comparing %s with %s', minion_id, regex) match = re.search(pattern, minion_id) if match and match.string == minion_id: log.debug('nsot external pillar found a match!') get_pillar = True break log.debug('nsot external pillar unable to find a match!') return get_pillar
[ "def", "_check_regex", "(", "minion_id", ",", "regex", ")", ":", "get_pillar", "=", "False", "for", "pattern", "in", "regex", ":", "log", ".", "debug", "(", "'nsot external pillar comparing %s with %s'", ",", "minion_id", ",", "regex", ")", "match", "=", "re",...
check whether or not this minion should have this external pillar returned :param minion_id: str :param minion_regex: list :return: bool
[ "check", "whether", "or", "not", "this", "minion", "should", "have", "this", "external", "pillar", "returned" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/nsot.py#L103-L120
train
saltstack/salt
salt/pillar/nsot.py
_query_nsot
def _query_nsot(url, headers, device=None): ''' if a device is given, query nsot for that specific device, otherwise return all devices :param url: str :param headers: dict :param device: None or str :return: ''' url = urlparse.urljoin(url, 'devices') ret = {} if not device: query = salt.utils.http.query(url, header_dict=headers, decode=True) else: url = urlparse.urljoin(url, device) query = salt.utils.http.query(url, header_dict=headers, decode=True) error = query.get('error') if error: log.error('can\'t get device(s) from nsot! reason: %s', error) else: ret = query['dict'] return ret
python
def _query_nsot(url, headers, device=None): ''' if a device is given, query nsot for that specific device, otherwise return all devices :param url: str :param headers: dict :param device: None or str :return: ''' url = urlparse.urljoin(url, 'devices') ret = {} if not device: query = salt.utils.http.query(url, header_dict=headers, decode=True) else: url = urlparse.urljoin(url, device) query = salt.utils.http.query(url, header_dict=headers, decode=True) error = query.get('error') if error: log.error('can\'t get device(s) from nsot! reason: %s', error) else: ret = query['dict'] return ret
[ "def", "_query_nsot", "(", "url", ",", "headers", ",", "device", "=", "None", ")", ":", "url", "=", "urlparse", ".", "urljoin", "(", "url", ",", "'devices'", ")", "ret", "=", "{", "}", "if", "not", "device", ":", "query", "=", "salt", ".", "utils",...
if a device is given, query nsot for that specific device, otherwise return all devices :param url: str :param headers: dict :param device: None or str :return:
[ "if", "a", "device", "is", "given", "query", "nsot", "for", "that", "specific", "device", "otherwise", "return", "all", "devices" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/nsot.py#L123-L147
train
saltstack/salt
salt/pillar/nsot.py
_proxy_info
def _proxy_info(minion_id, api_url, email, secret_key, fqdn_separator): ''' retrieve a dict of a device that exists in nsot :param minion_id: str :param api_url: str :param email: str :param secret_key: str :param fqdn_separator: str :return: dict ''' device_info = {} if fqdn_separator: minion_id = minion_id.replace('.', fqdn_separator) token = _get_token(api_url, email, secret_key) if token: headers = {'Authorization': 'AuthToken {}:{}'.format(email, token)} device_info = _query_nsot(api_url, headers, device=minion_id) return device_info
python
def _proxy_info(minion_id, api_url, email, secret_key, fqdn_separator): ''' retrieve a dict of a device that exists in nsot :param minion_id: str :param api_url: str :param email: str :param secret_key: str :param fqdn_separator: str :return: dict ''' device_info = {} if fqdn_separator: minion_id = minion_id.replace('.', fqdn_separator) token = _get_token(api_url, email, secret_key) if token: headers = {'Authorization': 'AuthToken {}:{}'.format(email, token)} device_info = _query_nsot(api_url, headers, device=minion_id) return device_info
[ "def", "_proxy_info", "(", "minion_id", ",", "api_url", ",", "email", ",", "secret_key", ",", "fqdn_separator", ")", ":", "device_info", "=", "{", "}", "if", "fqdn_separator", ":", "minion_id", "=", "minion_id", ".", "replace", "(", "'.'", ",", "fqdn_separat...
retrieve a dict of a device that exists in nsot :param minion_id: str :param api_url: str :param email: str :param secret_key: str :param fqdn_separator: str :return: dict
[ "retrieve", "a", "dict", "of", "a", "device", "that", "exists", "in", "nsot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/nsot.py#L150-L169
train
saltstack/salt
salt/pillar/nsot.py
_all_nsot_devices
def _all_nsot_devices(api_url, email, secret_key): ''' retrieve a list of all devices that exist in nsot :param api_url: str :param email: str :param secret_key: str :return: dict ''' token = _get_token(api_url, email, secret_key) all_devices = {} if token: headers = {'Authorization': 'AuthToken {}:{}'.format(email, token)} all_devices = _query_nsot(api_url, headers) return all_devices
python
def _all_nsot_devices(api_url, email, secret_key): ''' retrieve a list of all devices that exist in nsot :param api_url: str :param email: str :param secret_key: str :return: dict ''' token = _get_token(api_url, email, secret_key) all_devices = {} if token: headers = {'Authorization': 'AuthToken {}:{}'.format(email, token)} all_devices = _query_nsot(api_url, headers) return all_devices
[ "def", "_all_nsot_devices", "(", "api_url", ",", "email", ",", "secret_key", ")", ":", "token", "=", "_get_token", "(", "api_url", ",", "email", ",", "secret_key", ")", "all_devices", "=", "{", "}", "if", "token", ":", "headers", "=", "{", "'Authorization'...
retrieve a list of all devices that exist in nsot :param api_url: str :param email: str :param secret_key: str :return: dict
[ "retrieve", "a", "list", "of", "all", "devices", "that", "exist", "in", "nsot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/nsot.py#L172-L187
train
saltstack/salt
salt/pillar/nsot.py
ext_pillar
def ext_pillar(minion_id, pillar, api_url, email, secret_key, fqdn_separator=None, all_devices_regex=None, minion_regex=None): ''' Query NSoT API for network devices ''' ret = {} if minion_id == '*': log.info('There\'s no data to collect from NSoT for the Master') return ret if minion_regex: get_ext_pillar = _check_regex(minion_id, minion_regex) if get_ext_pillar: ret['nsot'] = _proxy_info(minion_id, api_url, email, secret_key, fqdn_separator) if all_devices_regex: get_ext_pillar = _check_regex(minion_id, all_devices_regex) if get_ext_pillar: if not ret.get('nsot'): ret['nsot'] = {} ret['nsot']['devices'] = _all_nsot_devices(api_url, email, secret_key) return ret
python
def ext_pillar(minion_id, pillar, api_url, email, secret_key, fqdn_separator=None, all_devices_regex=None, minion_regex=None): ''' Query NSoT API for network devices ''' ret = {} if minion_id == '*': log.info('There\'s no data to collect from NSoT for the Master') return ret if minion_regex: get_ext_pillar = _check_regex(minion_id, minion_regex) if get_ext_pillar: ret['nsot'] = _proxy_info(minion_id, api_url, email, secret_key, fqdn_separator) if all_devices_regex: get_ext_pillar = _check_regex(minion_id, all_devices_regex) if get_ext_pillar: if not ret.get('nsot'): ret['nsot'] = {} ret['nsot']['devices'] = _all_nsot_devices(api_url, email, secret_key) return ret
[ "def", "ext_pillar", "(", "minion_id", ",", "pillar", ",", "api_url", ",", "email", ",", "secret_key", ",", "fqdn_separator", "=", "None", ",", "all_devices_regex", "=", "None", ",", "minion_regex", "=", "None", ")", ":", "ret", "=", "{", "}", "if", "min...
Query NSoT API for network devices
[ "Query", "NSoT", "API", "for", "network", "devices" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/nsot.py#L190-L224
train
saltstack/salt
salt/states/incron.py
_check_cron
def _check_cron(user, path, mask, cmd): ''' Return the changes ''' arg_mask = mask.split(',') arg_mask.sort() lst = __salt__['incron.list_tab'](user) for cron in lst['crons']: if path == cron['path'] and cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): return 'update' return 'absent'
python
def _check_cron(user, path, mask, cmd): ''' Return the changes ''' arg_mask = mask.split(',') arg_mask.sort() lst = __salt__['incron.list_tab'](user) for cron in lst['crons']: if path == cron['path'] and cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): return 'update' return 'absent'
[ "def", "_check_cron", "(", "user", ",", "path", ",", "mask", ",", "cmd", ")", ":", "arg_mask", "=", "mask", ".", "split", "(", "','", ")", "arg_mask", ".", "sort", "(", ")", "lst", "=", "__salt__", "[", "'incron.list_tab'", "]", "(", "user", ")", "...
Return the changes
[ "Return", "the", "changes" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/incron.py#L48-L67
train
saltstack/salt
salt/states/incron.py
present
def present(name, path, mask, cmd, user='root'): ''' Verifies that the specified incron job is present for the specified user. For more advanced information about what exactly can be set in the cron timing parameters, check your incron system's documentation. Most Unix-like systems' incron documentation can be found via the incrontab man page: ``man 5 incrontab``. name Unique comment describing the entry path The path that should be watched user The name of the user who's crontab needs to be modified, defaults to the root user mask The mask of events that should be monitored for cmd The cmd that should be executed ''' mask = ',' . join(mask) ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} if __opts__['test']: status = _check_cron(user, path, mask, cmd) ret['result'] = None if status == 'absent': ret['comment'] = 'Incron {0} is set to be added'.format(name) elif status == 'present': ret['result'] = True ret['comment'] = 'Incron {0} already present'.format(name) elif status == 'update': ret['comment'] = 'Incron {0} is set to be updated'.format(name) return ret data = __salt__['incron.set_job'](user=user, path=path, mask=mask, cmd=cmd) if data == 'present': ret['comment'] = 'Incron {0} already present'.format(name) return ret if data == 'new': ret['comment'] = 'Incron {0} added to {1}\'s incrontab'.format(name, user) ret['changes'] = {user: name} return ret if data == 'updated': ret['comment'] = 'Incron {0} updated'.format(name) ret['changes'] = {user: name} return ret ret['comment'] = ('Incron {0} for user {1} failed to commit with error \n{2}' .format(name, user, data)) ret['result'] = False return ret
python
def present(name, path, mask, cmd, user='root'): ''' Verifies that the specified incron job is present for the specified user. For more advanced information about what exactly can be set in the cron timing parameters, check your incron system's documentation. Most Unix-like systems' incron documentation can be found via the incrontab man page: ``man 5 incrontab``. name Unique comment describing the entry path The path that should be watched user The name of the user who's crontab needs to be modified, defaults to the root user mask The mask of events that should be monitored for cmd The cmd that should be executed ''' mask = ',' . join(mask) ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} if __opts__['test']: status = _check_cron(user, path, mask, cmd) ret['result'] = None if status == 'absent': ret['comment'] = 'Incron {0} is set to be added'.format(name) elif status == 'present': ret['result'] = True ret['comment'] = 'Incron {0} already present'.format(name) elif status == 'update': ret['comment'] = 'Incron {0} is set to be updated'.format(name) return ret data = __salt__['incron.set_job'](user=user, path=path, mask=mask, cmd=cmd) if data == 'present': ret['comment'] = 'Incron {0} already present'.format(name) return ret if data == 'new': ret['comment'] = 'Incron {0} added to {1}\'s incrontab'.format(name, user) ret['changes'] = {user: name} return ret if data == 'updated': ret['comment'] = 'Incron {0} updated'.format(name) ret['changes'] = {user: name} return ret ret['comment'] = ('Incron {0} for user {1} failed to commit with error \n{2}' .format(name, user, data)) ret['result'] = False return ret
[ "def", "present", "(", "name", ",", "path", ",", "mask", ",", "cmd", ",", "user", "=", "'root'", ")", ":", "mask", "=", "','", ".", "join", "(", "mask", ")", "ret", "=", "{", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'name'...
Verifies that the specified incron job is present for the specified user. For more advanced information about what exactly can be set in the cron timing parameters, check your incron system's documentation. Most Unix-like systems' incron documentation can be found via the incrontab man page: ``man 5 incrontab``. name Unique comment describing the entry path The path that should be watched user The name of the user who's crontab needs to be modified, defaults to the root user mask The mask of events that should be monitored for cmd The cmd that should be executed
[ "Verifies", "that", "the", "specified", "incron", "job", "is", "present", "for", "the", "specified", "user", ".", "For", "more", "advanced", "information", "about", "what", "exactly", "can", "be", "set", "in", "the", "cron", "timing", "parameters", "check", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/incron.py#L90-L160
train
saltstack/salt
salt/runners/queue.py
insert
def insert(queue, items, backend='sqlite'): ''' Add an item or items to a queue CLI Example: .. code-block:: bash salt-run queue.insert myqueue myitem salt-run queue.insert myqueue "['item1', 'item2', 'item3']" salt-run queue.insert myqueue myitem backend=sqlite salt-run queue.insert myqueue "['item1', 'item2', 'item3']" backend=sqlite ''' queue_funcs = salt.loader.queues(__opts__) cmd = '{0}.insert'.format(backend) if cmd not in queue_funcs: raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) ret = queue_funcs[cmd](items=items, queue=queue) return ret
python
def insert(queue, items, backend='sqlite'): ''' Add an item or items to a queue CLI Example: .. code-block:: bash salt-run queue.insert myqueue myitem salt-run queue.insert myqueue "['item1', 'item2', 'item3']" salt-run queue.insert myqueue myitem backend=sqlite salt-run queue.insert myqueue "['item1', 'item2', 'item3']" backend=sqlite ''' queue_funcs = salt.loader.queues(__opts__) cmd = '{0}.insert'.format(backend) if cmd not in queue_funcs: raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) ret = queue_funcs[cmd](items=items, queue=queue) return ret
[ "def", "insert", "(", "queue", ",", "items", ",", "backend", "=", "'sqlite'", ")", ":", "queue_funcs", "=", "salt", ".", "loader", ".", "queues", "(", "__opts__", ")", "cmd", "=", "'{0}.insert'", ".", "format", "(", "backend", ")", "if", "cmd", "not", ...
Add an item or items to a queue CLI Example: .. code-block:: bash salt-run queue.insert myqueue myitem salt-run queue.insert myqueue "['item1', 'item2', 'item3']" salt-run queue.insert myqueue myitem backend=sqlite salt-run queue.insert myqueue "['item1', 'item2', 'item3']" backend=sqlite
[ "Add", "an", "item", "or", "items", "to", "a", "queue" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/queue.py#L75-L93
train
saltstack/salt
salt/runners/queue.py
list_queues
def list_queues(backend='sqlite'): ''' Return a list of Salt Queues on the backend CLI Example: .. code-block:: bash salt-run queue.list_queues salt-run queue.list_queues backend=sqlite ''' queue_funcs = salt.loader.queues(__opts__) cmd = '{0}.list_queues'.format(backend) if cmd not in queue_funcs: raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) ret = queue_funcs[cmd]() return ret
python
def list_queues(backend='sqlite'): ''' Return a list of Salt Queues on the backend CLI Example: .. code-block:: bash salt-run queue.list_queues salt-run queue.list_queues backend=sqlite ''' queue_funcs = salt.loader.queues(__opts__) cmd = '{0}.list_queues'.format(backend) if cmd not in queue_funcs: raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) ret = queue_funcs[cmd]() return ret
[ "def", "list_queues", "(", "backend", "=", "'sqlite'", ")", ":", "queue_funcs", "=", "salt", ".", "loader", ".", "queues", "(", "__opts__", ")", "cmd", "=", "'{0}.list_queues'", ".", "format", "(", "backend", ")", "if", "cmd", "not", "in", "queue_funcs", ...
Return a list of Salt Queues on the backend CLI Example: .. code-block:: bash salt-run queue.list_queues salt-run queue.list_queues backend=sqlite
[ "Return", "a", "list", "of", "Salt", "Queues", "on", "the", "backend" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/queue.py#L116-L132
train
saltstack/salt
salt/runners/queue.py
list_length
def list_length(queue, backend='sqlite'): ''' Provide the number of items in a queue CLI Example: .. code-block:: bash salt-run queue.list_length myqueue salt-run queue.list_length myqueue backend=sqlite ''' queue_funcs = salt.loader.queues(__opts__) cmd = '{0}.list_length'.format(backend) if cmd not in queue_funcs: raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) ret = queue_funcs[cmd](queue=queue) return ret
python
def list_length(queue, backend='sqlite'): ''' Provide the number of items in a queue CLI Example: .. code-block:: bash salt-run queue.list_length myqueue salt-run queue.list_length myqueue backend=sqlite ''' queue_funcs = salt.loader.queues(__opts__) cmd = '{0}.list_length'.format(backend) if cmd not in queue_funcs: raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) ret = queue_funcs[cmd](queue=queue) return ret
[ "def", "list_length", "(", "queue", ",", "backend", "=", "'sqlite'", ")", ":", "queue_funcs", "=", "salt", ".", "loader", ".", "queues", "(", "__opts__", ")", "cmd", "=", "'{0}.list_length'", ".", "format", "(", "backend", ")", "if", "cmd", "not", "in", ...
Provide the number of items in a queue CLI Example: .. code-block:: bash salt-run queue.list_length myqueue salt-run queue.list_length myqueue backend=sqlite
[ "Provide", "the", "number", "of", "items", "in", "a", "queue" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/queue.py#L135-L151
train
saltstack/salt
salt/runners/queue.py
pop
def pop(queue, quantity=1, backend='sqlite', is_runner=False): ''' Pop one or more or all items from a queue CLI Example: .. code-block:: bash salt-run queue.pop myqueue salt-run queue.pop myqueue 6 salt-run queue.pop myqueue all salt-run queue.pop myqueue 6 backend=sqlite salt-run queue.pop myqueue all backend=sqlite ''' queue_funcs = salt.loader.queues(__opts__) cmd = '{0}.pop'.format(backend) if cmd not in queue_funcs: raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) ret = queue_funcs[cmd](quantity=quantity, queue=queue, is_runner=is_runner) return ret
python
def pop(queue, quantity=1, backend='sqlite', is_runner=False): ''' Pop one or more or all items from a queue CLI Example: .. code-block:: bash salt-run queue.pop myqueue salt-run queue.pop myqueue 6 salt-run queue.pop myqueue all salt-run queue.pop myqueue 6 backend=sqlite salt-run queue.pop myqueue all backend=sqlite ''' queue_funcs = salt.loader.queues(__opts__) cmd = '{0}.pop'.format(backend) if cmd not in queue_funcs: raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) ret = queue_funcs[cmd](quantity=quantity, queue=queue, is_runner=is_runner) return ret
[ "def", "pop", "(", "queue", ",", "quantity", "=", "1", ",", "backend", "=", "'sqlite'", ",", "is_runner", "=", "False", ")", ":", "queue_funcs", "=", "salt", ".", "loader", ".", "queues", "(", "__opts__", ")", "cmd", "=", "'{0}.pop'", ".", "format", ...
Pop one or more or all items from a queue CLI Example: .. code-block:: bash salt-run queue.pop myqueue salt-run queue.pop myqueue 6 salt-run queue.pop myqueue all salt-run queue.pop myqueue 6 backend=sqlite salt-run queue.pop myqueue all backend=sqlite
[ "Pop", "one", "or", "more", "or", "all", "items", "from", "a", "queue" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/queue.py#L173-L192
train
saltstack/salt
salt/runners/queue.py
process_queue
def process_queue(queue, quantity=1, backend='sqlite', is_runner=False): ''' Pop items off a queue and create an event on the Salt event bus to be processed by a Reactor. CLI Example: .. code-block:: bash salt-run queue.process_queue myqueue salt-run queue.process_queue myqueue 6 salt-run queue.process_queue myqueue all backend=sqlite ''' # get ready to send an event event = get_event( 'master', __opts__['sock_dir'], __opts__['transport'], opts=__opts__, listen=False) try: items = pop(queue=queue, quantity=quantity, backend=backend, is_runner=is_runner) except SaltInvocationError as exc: error_txt = '{0}'.format(exc) __jid_event__.fire_event({'errors': error_txt}, 'progress') return False data = {'items': items, 'backend': backend, 'queue': queue, } event.fire_event(data, tagify([queue, 'process'], prefix='queue')) return data
python
def process_queue(queue, quantity=1, backend='sqlite', is_runner=False): ''' Pop items off a queue and create an event on the Salt event bus to be processed by a Reactor. CLI Example: .. code-block:: bash salt-run queue.process_queue myqueue salt-run queue.process_queue myqueue 6 salt-run queue.process_queue myqueue all backend=sqlite ''' # get ready to send an event event = get_event( 'master', __opts__['sock_dir'], __opts__['transport'], opts=__opts__, listen=False) try: items = pop(queue=queue, quantity=quantity, backend=backend, is_runner=is_runner) except SaltInvocationError as exc: error_txt = '{0}'.format(exc) __jid_event__.fire_event({'errors': error_txt}, 'progress') return False data = {'items': items, 'backend': backend, 'queue': queue, } event.fire_event(data, tagify([queue, 'process'], prefix='queue')) return data
[ "def", "process_queue", "(", "queue", ",", "quantity", "=", "1", ",", "backend", "=", "'sqlite'", ",", "is_runner", "=", "False", ")", ":", "# get ready to send an event", "event", "=", "get_event", "(", "'master'", ",", "__opts__", "[", "'sock_dir'", "]", "...
Pop items off a queue and create an event on the Salt event bus to be processed by a Reactor. CLI Example: .. code-block:: bash salt-run queue.process_queue myqueue salt-run queue.process_queue myqueue 6 salt-run queue.process_queue myqueue all backend=sqlite
[ "Pop", "items", "off", "a", "queue", "and", "create", "an", "event", "on", "the", "Salt", "event", "bus", "to", "be", "processed", "by", "a", "Reactor", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/queue.py#L195-L227
train
saltstack/salt
salt/runners/queue.py
__get_queue_opts
def __get_queue_opts(queue=None, backend=None): ''' Get consistent opts for the queued runners ''' if queue is None: queue = __opts__.get('runner_queue', {}).get('queue') if backend is None: backend = __opts__.get('runner_queue', {}).get('backend', 'pgjsonb') return {'backend': backend, 'queue': queue}
python
def __get_queue_opts(queue=None, backend=None): ''' Get consistent opts for the queued runners ''' if queue is None: queue = __opts__.get('runner_queue', {}).get('queue') if backend is None: backend = __opts__.get('runner_queue', {}).get('backend', 'pgjsonb') return {'backend': backend, 'queue': queue}
[ "def", "__get_queue_opts", "(", "queue", "=", "None", ",", "backend", "=", "None", ")", ":", "if", "queue", "is", "None", ":", "queue", "=", "__opts__", ".", "get", "(", "'runner_queue'", ",", "{", "}", ")", ".", "get", "(", "'queue'", ")", "if", "...
Get consistent opts for the queued runners
[ "Get", "consistent", "opts", "for", "the", "queued", "runners" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/queue.py#L230-L239
train
saltstack/salt
salt/runners/queue.py
insert_runner
def insert_runner(fun, args=None, kwargs=None, queue=None, backend=None): ''' Insert a reference to a runner into the queue so that it can be run later. fun The runner function that is going to be run args list or comma-seperated string of args to send to fun kwargs dictionary of keyword arguments to send to fun queue queue to insert the runner reference into backend backend that to use for the queue CLI Example: .. code-block:: bash salt-run queue.insert_runner test.stdout_print salt-run queue.insert_runner event.send test_insert_runner kwargs='{"data": {"foo": "bar"}}' ''' if args is None: args = [] elif isinstance(args, six.string_types): args = args.split(',') if kwargs is None: kwargs = {} queue_kwargs = __get_queue_opts(queue=queue, backend=backend) data = {'fun': fun, 'args': args, 'kwargs': kwargs} return insert(items=data, **queue_kwargs)
python
def insert_runner(fun, args=None, kwargs=None, queue=None, backend=None): ''' Insert a reference to a runner into the queue so that it can be run later. fun The runner function that is going to be run args list or comma-seperated string of args to send to fun kwargs dictionary of keyword arguments to send to fun queue queue to insert the runner reference into backend backend that to use for the queue CLI Example: .. code-block:: bash salt-run queue.insert_runner test.stdout_print salt-run queue.insert_runner event.send test_insert_runner kwargs='{"data": {"foo": "bar"}}' ''' if args is None: args = [] elif isinstance(args, six.string_types): args = args.split(',') if kwargs is None: kwargs = {} queue_kwargs = __get_queue_opts(queue=queue, backend=backend) data = {'fun': fun, 'args': args, 'kwargs': kwargs} return insert(items=data, **queue_kwargs)
[ "def", "insert_runner", "(", "fun", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "queue", "=", "None", ",", "backend", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "elif", "isinstance", "(", "args", ...
Insert a reference to a runner into the queue so that it can be run later. fun The runner function that is going to be run args list or comma-seperated string of args to send to fun kwargs dictionary of keyword arguments to send to fun queue queue to insert the runner reference into backend backend that to use for the queue CLI Example: .. code-block:: bash salt-run queue.insert_runner test.stdout_print salt-run queue.insert_runner event.send test_insert_runner kwargs='{"data": {"foo": "bar"}}'
[ "Insert", "a", "reference", "to", "a", "runner", "into", "the", "queue", "so", "that", "it", "can", "be", "run", "later", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/queue.py#L242-L277
train
saltstack/salt
salt/runners/queue.py
process_runner
def process_runner(quantity=1, queue=None, backend=None): ''' Process queued runners quantity number of runners to process queue queue to insert the runner reference into backend backend that to use for the queue CLI Example: .. code-block:: bash salt-run queue.process_runner salt-run queue.process_runner 5 ''' queue_kwargs = __get_queue_opts(queue=queue, backend=backend) data = process_queue(quantity=quantity, is_runner=True, **queue_kwargs) for job in data['items']: __salt__[job['fun']](*job['args'], **job['kwargs'])
python
def process_runner(quantity=1, queue=None, backend=None): ''' Process queued runners quantity number of runners to process queue queue to insert the runner reference into backend backend that to use for the queue CLI Example: .. code-block:: bash salt-run queue.process_runner salt-run queue.process_runner 5 ''' queue_kwargs = __get_queue_opts(queue=queue, backend=backend) data = process_queue(quantity=quantity, is_runner=True, **queue_kwargs) for job in data['items']: __salt__[job['fun']](*job['args'], **job['kwargs'])
[ "def", "process_runner", "(", "quantity", "=", "1", ",", "queue", "=", "None", ",", "backend", "=", "None", ")", ":", "queue_kwargs", "=", "__get_queue_opts", "(", "queue", "=", "queue", ",", "backend", "=", "backend", ")", "data", "=", "process_queue", ...
Process queued runners quantity number of runners to process queue queue to insert the runner reference into backend backend that to use for the queue CLI Example: .. code-block:: bash salt-run queue.process_runner salt-run queue.process_runner 5
[ "Process", "queued", "runners" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/queue.py#L280-L304
train
saltstack/salt
salt/modules/publish.py
_parse_args
def _parse_args(arg): ''' yamlify `arg` and ensure it's outermost datatype is a list ''' yaml_args = salt.utils.args.yamlify_arg(arg) if yaml_args is None: return [] elif not isinstance(yaml_args, list): return [yaml_args] else: return yaml_args
python
def _parse_args(arg): ''' yamlify `arg` and ensure it's outermost datatype is a list ''' yaml_args = salt.utils.args.yamlify_arg(arg) if yaml_args is None: return [] elif not isinstance(yaml_args, list): return [yaml_args] else: return yaml_args
[ "def", "_parse_args", "(", "arg", ")", ":", "yaml_args", "=", "salt", ".", "utils", ".", "args", ".", "yamlify_arg", "(", "arg", ")", "if", "yaml_args", "is", "None", ":", "return", "[", "]", "elif", "not", "isinstance", "(", "yaml_args", ",", "list", ...
yamlify `arg` and ensure it's outermost datatype is a list
[ "yamlify", "arg", "and", "ensure", "it", "s", "outermost", "datatype", "is", "a", "list" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/publish.py#L27-L38
train
saltstack/salt
salt/modules/publish.py
_publish
def _publish( tgt, fun, arg=None, tgt_type='glob', returner='', timeout=5, form='clean', wait=False, via_master=None): ''' Publish a command from the minion out to other minions, publications need to be enabled on the Salt master and the minion needs to have permission to publish the command. The Salt master will also prevent a recursive publication loop, this means that a minion cannot command another minion to command another minion as that would create an infinite command loop. The arguments sent to the minion publish function are separated with commas. This means that for a minion executing a command with multiple args it will look like this:: salt system.example.com publish.publish '*' user.add 'foo,1020,1020' CLI Example: .. code-block:: bash salt system.example.com publish.publish '*' cmd.run 'ls -la /tmp' ''' if 'master_uri' not in __opts__: log.error('Cannot run publish commands without a connection to a salt master. No command sent.') return {} if fun.startswith('publish.'): log.info('Cannot publish publish calls. Returning {}') return {} arg = _parse_args(arg) if via_master: if 'master_uri_list' not in __opts__: raise SaltInvocationError(message='Could not find list of masters \ in minion configuration but `via_master` was specified.') else: # Find the master in the list of master_uris generated by the minion base class matching_master_uris = [master for master in __opts__['master_uri_list'] if '//{0}:'.format(via_master) in master] if not matching_master_uris: raise SaltInvocationError('Could not find match for {0} in \ list of configured masters {1} when using `via_master` option'.format( via_master, __opts__['master_uri_list'])) if len(matching_master_uris) > 1: # If we have multiple matches, consider this a non-fatal error # and continue with whatever we found first. log.warning('The `via_master` flag found ' 'more than one possible match found for %s when ' 'evaluating list %s', via_master, __opts__['master_uri_list']) master_uri = matching_master_uris.pop() else: # If no preference is expressed by the user, just publish to the first master # in the list. master_uri = __opts__['master_uri'] log.info('Publishing \'%s\' to %s', fun, master_uri) auth = salt.crypt.SAuth(__opts__) tok = auth.gen_token(b'salt') load = {'cmd': 'minion_pub', 'fun': fun, 'arg': arg, 'tgt': tgt, 'tgt_type': tgt_type, 'ret': returner, 'tok': tok, 'tmo': timeout, 'form': form, 'id': __opts__['id'], 'no_parse': __opts__.get('no_parse', [])} channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master_uri) try: try: peer_data = channel.send(load) except SaltReqTimeoutError: return '\'{0}\' publish timed out'.format(fun) if not peer_data: return {} # CLI args are passed as strings, re-cast to keep time.sleep happy if wait: loop_interval = 0.3 matched_minions = set(peer_data['minions']) returned_minions = set() loop_counter = 0 while returned_minions ^ matched_minions: load = {'cmd': 'pub_ret', 'id': __opts__['id'], 'tok': tok, 'jid': peer_data['jid']} ret = channel.send(load) returned_minions = set(ret.keys()) end_loop = False if returned_minions >= matched_minions: end_loop = True elif (loop_interval * loop_counter) > timeout: # This may be unnecessary, but I am paranoid if not returned_minions: return {} end_loop = True if end_loop: if form == 'clean': cret = {} for host in ret: cret[host] = ret[host]['ret'] return cret else: return ret loop_counter = loop_counter + 1 time.sleep(loop_interval) else: time.sleep(float(timeout)) load = {'cmd': 'pub_ret', 'id': __opts__['id'], 'tok': tok, 'jid': peer_data['jid']} ret = channel.send(load) if form == 'clean': cret = {} for host in ret: cret[host] = ret[host]['ret'] return cret else: return ret finally: channel.close() return {}
python
def _publish( tgt, fun, arg=None, tgt_type='glob', returner='', timeout=5, form='clean', wait=False, via_master=None): ''' Publish a command from the minion out to other minions, publications need to be enabled on the Salt master and the minion needs to have permission to publish the command. The Salt master will also prevent a recursive publication loop, this means that a minion cannot command another minion to command another minion as that would create an infinite command loop. The arguments sent to the minion publish function are separated with commas. This means that for a minion executing a command with multiple args it will look like this:: salt system.example.com publish.publish '*' user.add 'foo,1020,1020' CLI Example: .. code-block:: bash salt system.example.com publish.publish '*' cmd.run 'ls -la /tmp' ''' if 'master_uri' not in __opts__: log.error('Cannot run publish commands without a connection to a salt master. No command sent.') return {} if fun.startswith('publish.'): log.info('Cannot publish publish calls. Returning {}') return {} arg = _parse_args(arg) if via_master: if 'master_uri_list' not in __opts__: raise SaltInvocationError(message='Could not find list of masters \ in minion configuration but `via_master` was specified.') else: # Find the master in the list of master_uris generated by the minion base class matching_master_uris = [master for master in __opts__['master_uri_list'] if '//{0}:'.format(via_master) in master] if not matching_master_uris: raise SaltInvocationError('Could not find match for {0} in \ list of configured masters {1} when using `via_master` option'.format( via_master, __opts__['master_uri_list'])) if len(matching_master_uris) > 1: # If we have multiple matches, consider this a non-fatal error # and continue with whatever we found first. log.warning('The `via_master` flag found ' 'more than one possible match found for %s when ' 'evaluating list %s', via_master, __opts__['master_uri_list']) master_uri = matching_master_uris.pop() else: # If no preference is expressed by the user, just publish to the first master # in the list. master_uri = __opts__['master_uri'] log.info('Publishing \'%s\' to %s', fun, master_uri) auth = salt.crypt.SAuth(__opts__) tok = auth.gen_token(b'salt') load = {'cmd': 'minion_pub', 'fun': fun, 'arg': arg, 'tgt': tgt, 'tgt_type': tgt_type, 'ret': returner, 'tok': tok, 'tmo': timeout, 'form': form, 'id': __opts__['id'], 'no_parse': __opts__.get('no_parse', [])} channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master_uri) try: try: peer_data = channel.send(load) except SaltReqTimeoutError: return '\'{0}\' publish timed out'.format(fun) if not peer_data: return {} # CLI args are passed as strings, re-cast to keep time.sleep happy if wait: loop_interval = 0.3 matched_minions = set(peer_data['minions']) returned_minions = set() loop_counter = 0 while returned_minions ^ matched_minions: load = {'cmd': 'pub_ret', 'id': __opts__['id'], 'tok': tok, 'jid': peer_data['jid']} ret = channel.send(load) returned_minions = set(ret.keys()) end_loop = False if returned_minions >= matched_minions: end_loop = True elif (loop_interval * loop_counter) > timeout: # This may be unnecessary, but I am paranoid if not returned_minions: return {} end_loop = True if end_loop: if form == 'clean': cret = {} for host in ret: cret[host] = ret[host]['ret'] return cret else: return ret loop_counter = loop_counter + 1 time.sleep(loop_interval) else: time.sleep(float(timeout)) load = {'cmd': 'pub_ret', 'id': __opts__['id'], 'tok': tok, 'jid': peer_data['jid']} ret = channel.send(load) if form == 'clean': cret = {} for host in ret: cret[host] = ret[host]['ret'] return cret else: return ret finally: channel.close() return {}
[ "def", "_publish", "(", "tgt", ",", "fun", ",", "arg", "=", "None", ",", "tgt_type", "=", "'glob'", ",", "returner", "=", "''", ",", "timeout", "=", "5", ",", "form", "=", "'clean'", ",", "wait", "=", "False", ",", "via_master", "=", "None", ")", ...
Publish a command from the minion out to other minions, publications need to be enabled on the Salt master and the minion needs to have permission to publish the command. The Salt master will also prevent a recursive publication loop, this means that a minion cannot command another minion to command another minion as that would create an infinite command loop. The arguments sent to the minion publish function are separated with commas. This means that for a minion executing a command with multiple args it will look like this:: salt system.example.com publish.publish '*' user.add 'foo,1020,1020' CLI Example: .. code-block:: bash salt system.example.com publish.publish '*' cmd.run 'ls -la /tmp'
[ "Publish", "a", "command", "from", "the", "minion", "out", "to", "other", "minions", "publications", "need", "to", "be", "enabled", "on", "the", "Salt", "master", "and", "the", "minion", "needs", "to", "have", "permission", "to", "publish", "the", "command",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/publish.py#L41-L179
train
saltstack/salt
salt/modules/publish.py
publish
def publish(tgt, fun, arg=None, tgt_type='glob', returner='', timeout=5, via_master=None): ''' Publish a command from the minion out to other minions. Publications need to be enabled on the Salt master and the minion needs to have permission to publish the command. The Salt master will also prevent a recursive publication loop, this means that a minion cannot command another minion to command another minion as that would create an infinite command loop. The ``tgt_type`` argument is used to pass a target other than a glob into the execution, the available options are: - glob - pcre - grain - grain_pcre - pillar - pillar_pcre - ipcidr - range - compound .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Note that for pillar matches must be exact, both in the pillar matcher and the compound matcher. No globbing is supported. The arguments sent to the minion publish function are separated with commas. This means that for a minion executing a command with multiple args it will look like this: .. code-block:: bash salt system.example.com publish.publish '*' user.add 'foo,1020,1020' salt system.example.com publish.publish 'os:Fedora' network.interfaces '' grain CLI Example: .. code-block:: bash salt system.example.com publish.publish '*' cmd.run 'ls -la /tmp' .. admonition:: Attention If you need to pass a value to a function argument and that value contains an equal sign, you **must** include the argument name. For example: .. code-block:: bash salt '*' publish.publish test.kwarg arg='cheese=spam' Multiple keyword arguments should be passed as a list. .. code-block:: bash salt '*' publish.publish test.kwarg arg="['cheese=spam','spam=cheese']" When running via salt-call, the `via_master` flag may be set to specific which master the publication should be sent to. Only one master may be specified. If unset, the publication will be sent only to the first master in minion configuration. ''' return _publish(tgt, fun, arg=arg, tgt_type=tgt_type, returner=returner, timeout=timeout, form='clean', wait=True, via_master=via_master)
python
def publish(tgt, fun, arg=None, tgt_type='glob', returner='', timeout=5, via_master=None): ''' Publish a command from the minion out to other minions. Publications need to be enabled on the Salt master and the minion needs to have permission to publish the command. The Salt master will also prevent a recursive publication loop, this means that a minion cannot command another minion to command another minion as that would create an infinite command loop. The ``tgt_type`` argument is used to pass a target other than a glob into the execution, the available options are: - glob - pcre - grain - grain_pcre - pillar - pillar_pcre - ipcidr - range - compound .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Note that for pillar matches must be exact, both in the pillar matcher and the compound matcher. No globbing is supported. The arguments sent to the minion publish function are separated with commas. This means that for a minion executing a command with multiple args it will look like this: .. code-block:: bash salt system.example.com publish.publish '*' user.add 'foo,1020,1020' salt system.example.com publish.publish 'os:Fedora' network.interfaces '' grain CLI Example: .. code-block:: bash salt system.example.com publish.publish '*' cmd.run 'ls -la /tmp' .. admonition:: Attention If you need to pass a value to a function argument and that value contains an equal sign, you **must** include the argument name. For example: .. code-block:: bash salt '*' publish.publish test.kwarg arg='cheese=spam' Multiple keyword arguments should be passed as a list. .. code-block:: bash salt '*' publish.publish test.kwarg arg="['cheese=spam','spam=cheese']" When running via salt-call, the `via_master` flag may be set to specific which master the publication should be sent to. Only one master may be specified. If unset, the publication will be sent only to the first master in minion configuration. ''' return _publish(tgt, fun, arg=arg, tgt_type=tgt_type, returner=returner, timeout=timeout, form='clean', wait=True, via_master=via_master)
[ "def", "publish", "(", "tgt", ",", "fun", ",", "arg", "=", "None", ",", "tgt_type", "=", "'glob'", ",", "returner", "=", "''", ",", "timeout", "=", "5", ",", "via_master", "=", "None", ")", ":", "return", "_publish", "(", "tgt", ",", "fun", ",", ...
Publish a command from the minion out to other minions. Publications need to be enabled on the Salt master and the minion needs to have permission to publish the command. The Salt master will also prevent a recursive publication loop, this means that a minion cannot command another minion to command another minion as that would create an infinite command loop. The ``tgt_type`` argument is used to pass a target other than a glob into the execution, the available options are: - glob - pcre - grain - grain_pcre - pillar - pillar_pcre - ipcidr - range - compound .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Note that for pillar matches must be exact, both in the pillar matcher and the compound matcher. No globbing is supported. The arguments sent to the minion publish function are separated with commas. This means that for a minion executing a command with multiple args it will look like this: .. code-block:: bash salt system.example.com publish.publish '*' user.add 'foo,1020,1020' salt system.example.com publish.publish 'os:Fedora' network.interfaces '' grain CLI Example: .. code-block:: bash salt system.example.com publish.publish '*' cmd.run 'ls -la /tmp' .. admonition:: Attention If you need to pass a value to a function argument and that value contains an equal sign, you **must** include the argument name. For example: .. code-block:: bash salt '*' publish.publish test.kwarg arg='cheese=spam' Multiple keyword arguments should be passed as a list. .. code-block:: bash salt '*' publish.publish test.kwarg arg="['cheese=spam','spam=cheese']" When running via salt-call, the `via_master` flag may be set to specific which master the publication should be sent to. Only one master may be specified. If unset, the publication will be sent only to the first master in minion configuration.
[ "Publish", "a", "command", "from", "the", "minion", "out", "to", "other", "minions", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/publish.py#L182-L263
train
saltstack/salt
salt/modules/publish.py
full_data
def full_data(tgt, fun, arg=None, tgt_type='glob', returner='', timeout=5): ''' Return the full data about the publication, this is invoked in the same way as the publish function CLI Example: .. code-block:: bash salt system.example.com publish.full_data '*' cmd.run 'ls -la /tmp' .. admonition:: Attention If you need to pass a value to a function argument and that value contains an equal sign, you **must** include the argument name. For example: .. code-block:: bash salt '*' publish.full_data test.kwarg arg='cheese=spam' ''' return _publish(tgt, fun, arg=arg, tgt_type=tgt_type, returner=returner, timeout=timeout, form='full', wait=True)
python
def full_data(tgt, fun, arg=None, tgt_type='glob', returner='', timeout=5): ''' Return the full data about the publication, this is invoked in the same way as the publish function CLI Example: .. code-block:: bash salt system.example.com publish.full_data '*' cmd.run 'ls -la /tmp' .. admonition:: Attention If you need to pass a value to a function argument and that value contains an equal sign, you **must** include the argument name. For example: .. code-block:: bash salt '*' publish.full_data test.kwarg arg='cheese=spam' ''' return _publish(tgt, fun, arg=arg, tgt_type=tgt_type, returner=returner, timeout=timeout, form='full', wait=True)
[ "def", "full_data", "(", "tgt", ",", "fun", ",", "arg", "=", "None", ",", "tgt_type", "=", "'glob'", ",", "returner", "=", "''", ",", "timeout", "=", "5", ")", ":", "return", "_publish", "(", "tgt", ",", "fun", ",", "arg", "=", "arg", ",", "tgt_t...
Return the full data about the publication, this is invoked in the same way as the publish function CLI Example: .. code-block:: bash salt system.example.com publish.full_data '*' cmd.run 'ls -la /tmp' .. admonition:: Attention If you need to pass a value to a function argument and that value contains an equal sign, you **must** include the argument name. For example: .. code-block:: bash salt '*' publish.full_data test.kwarg arg='cheese=spam'
[ "Return", "the", "full", "data", "about", "the", "publication", "this", "is", "invoked", "in", "the", "same", "way", "as", "the", "publish", "function" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/publish.py#L266-L300
train