question
stringlengths 11
28.2k
| answer
stringlengths 26
27.7k
| tag
stringclasses 130
values | question_id
int64 935
78.4M
| score
int64 10
5.49k
|
---|---|---|---|---|
I am facing a strange situation where I am using gitlab account to handle my code. I am using ssh protocol to access the repo. I am able to pull the code but I am receiving the following error while I try to push the code. This could be something silly on my side. But I have the keys stored in my gitlab profile and able to use it to pull the code.
Error :
$ git push origin master
key_load_public: invalid format
Enter passphrase for key '/c/Users/username/.ssh/id_rsa':
Access denied.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
| Finally I have been able to resolve this issue and I am posting it for other users. If the keys generated by putty is not helping you to access the gitlab repo, try generating the keys from gitbash terminal using the command ssh-keygen and save the files in .ssh folder of your user account.
The linux style key generation made my life easy as I was trying to generate key in windows environment with putty keygen.
Hope this helps somebody.
| GitLab | 33,302,130 | 16 |
I've been following the instructions from the GitLab wiki, however, it seems as if some key pieces of information are missing. In the section "Using a Non-Bundled Web Server" it never explains how I need to reconfigure my Nginx installation to reverse proxy over to GitLab.
Basically, I'd like to have GitLab installed under git.example.com, but I can't seem to find the configuration settings for my existing Nginx installation that'll do that. The wiki page goes on to talk about configuring an existing Passenger/Nginx installation, but I don't have Passenger, so I don't think that applies to my situation.
I suppose the easiest solution would be if there were a way to tell Gitlab to use it's built-in Nginx and just listen on an internal port, and then have my other Nginx forward to that port, but I can't seem to figure out how to configure Gitlab to handle that.
Any help would be greatly appreciated.
| I got it working! So insanely excited!
So as I said, I was attempting to follow these instructions, but I wasn't getting anywhere, since it seemed to be lacking instructions on how to make your existing Nginx install link into Gitlab.
Well, further down on the page they have a more complete explanation for Using an Existing Passenger / Nginx Installation, and while at first that didn't seem like what I wanted, researching Passenger a bit made it clear that it wasn't a Ruby-only thing(their easily-found install instructions require you to install it as a ruby gem) and their instructions for Ubuntu installation allowed me to integrate it into my existing Nginx reasonably easily.
From there, it was just follow the steps in the wiki, although with a couple changes.
The Existing Passenger/Nginx Installation section fails to mention what the previous section on non-bundled Nginx install says, that you need to add www-data to the web_server['external_users'] line in the gitlab.rb file.
Since I reconfigured my Gitlab installation to remove the bundled Nginx before I ran it the first time, the nginx log file at /var/log/gitlab/nginx/gitlab_access.log was non-existent, and this caused an error when Nginx tried to start up, simply creating that blank file and giving it proper read/write access made it work like a charm.
I'm super psyched now, hope anyone who has as specific of a problem in the future comes across this, that Wiki should really be updated to simply remove/merge those two sections and explain/link to how to install Passenger into an existing Nginx installation. Would have saved me a lot of confusion and wasted time.
| GitLab | 29,403,212 | 16 |
I have a Git/Gitlab repository. We used to commit straight to master, but we decided to switch to using feature branches like the rest of the world for this release.
We need to reset our remote master to the state it was in immediately after the last release. If someone has already committed to the master directly, how can I reset it to a clean state, removing all history past the last release?
I've spent about an hour googling now and can't find an answer to this specific question. Sorry if it seems redundant, it seems like such a simple task with no obvious answer!
| To reset a local branch,
git branch -f master last-release
To reset a remote branch,
git push -f origin last-release:master
where last-release is the ref (commit id or branch) you want to reset master to.
(Neither of these affect your working tree; you can even do these from a bare repo, if you wish.)
| GitLab | 22,674,267 | 16 |
I'm new to gitlab and CI so i had tons of questions but some of them solved via google, SO, git mans, but not the last ...
I can't clone repo via ssh =(
If i try to clone repo via http:
lesha@lesha-SeoTeam:/var/www$ git clone http://gitlab.vbox/root/virtualboxgitlab.git
Cloning into 'virtualboxgitlab'...
Username for 'http://gitlab.vbox': root
Password for 'http://[email protected]':
warning: You appear to have cloned an empty repository.
That's OK!
But via ssh ...
lesha@lesha-SeoTeam:/var/www$ git clone [email protected]:root/virtualboxgitlab.git
Cloning into virtualbox 'gitlab'
[email protected]'s password:<br />
It prompts me git's password which I didn't create during install (as I had in man)
rsa keys
I added my key via gitlab's web (to account root, actually I didn't create any other accounts)
And also I added key by "cat my_rsa.pub >> authorized_keys"
I read few posts here about ssh troubles, but most have gitolite installed
I installed gitlab 5.3 without gitolite (as in manual), may be I should ?
Also I tried ssh -vT [email protected] and it outputs :
....
debug1: Server host key: ECDSA 48:83:ba:b3:37:72:a0:dc:ca:2c:a3:b8:78:a1:c4:ad
debug1: Host 'gitlab.vbox' is known and matches the ECDSA host key.
debug1: Found key in /home/lesha/.ssh/known_hosts:2
debug1: ssh_ecdsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/lesha/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/lesha/.ssh/id_dsa
debug1: Trying private key: /home/lesha/.ssh/id_ecdsa
debug1: Next authentication method: password
[email protected]'s password:
root@seotm-server:/home/git/.ssh# ls -l
итого 4
-rw------- 1 git git 922 Июл 18 21:05 authorized_keys
environmetnt:
debian 7, nginx + passenger, gitlab 5.3, ruby 2.0.0p247 , without gitolite, puma against unicorn
please help!=) i'm stuck ...
some additions (20.07.2013):
I created user git as in manual install
sudo adduser --disabled-login --gecos 'GitLab' git
The next day, I tried to kill git and re-add simply by useradd command, after that my keys are working but i'm still not happy because:
lesha@lesha-SeoTeam:/var/www$ git clone [email protected]:root/virtualboxgitlab.git
Cloning into 'virtualboxgitlab'...
fatal: 'root/virtualboxgitlab.git' does not appear to be a git repository
fatal: The remote end hung up unexpectedly
and http works as well as previous:
lesha@lesha-SeoTeam:/var/www$ git clone http://gitlab.vbox/root/virtualboxgitlab.git
Cloning into 'virtualboxgitlab'...
Username for 'http://gitlab.vbox': root
Password for 'http://[email protected]':
warning: You appear to have cloned an empty repository.
So, now I don't have auth problems but have another one.
How would you troubleshoot this issue from there?
| GitLab 5.x doesn't use gitolite anymore, but gitlab-shell.
I would advise to create a dedicated account, as recommended in the installation process.
ssh [email protected]
That ssh commands means you are asking for a secure shell on 'gitlab.vbox' as user 'git'. If that user doesn't exist... it won't work.
There is no need to try and clone repo is the tests doesn't run properly:
sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production
The OP reports ssh works better after creating the git user and adding the keys, but:
first make sure you create your keys on a 'client' account', not in ~git/.ssh/id_rsa: you are trying to open a session as git, from a client account. git is the account in which gitlab is installed.
You should then register your public key in the ssh page of the user account you declare through the gitlab gui. You should not "useradd" an ssh to root.
If you see this:
lesha@lesha-SeoTeam:/var/www$ git clone [email protected]:root/virtualboxgitlab.git
Cloning into 'virtualboxgitlab'...
fatal: 'root/virtualboxgitlab.git' does not appear to be a git repository
fatal: The remote end hung up unexpectedly
That also means you shouldn't specify the path of the repo (root/):
git clone [email protected]:virtualboxgitlab.git
It is gitlab job to know where virtualboxgitlab.git is stored (as specified in its gitlab.yml config file)
Basically, forget root, and do the full installation of gitlab as it was intended: in a 'git' account.
The OP made it work, commenting that:
"root" is administrators namespace, gitlab creates this url automatically and without it clone doesn't work, now everything clones and I begin to install gitlab CI,
The OP had to:
add my user to sudo group, made clean install, received error
/usr/local/lib/ruby/2.0.0/net/http.rb:878:in initialize': getaddrinfo:
Name or service not known (SocketError)
which can't resolve hostname, added gitlab.vbox to /etc/hosts
| GitLab | 17,739,978 | 16 |
After the first release of our product, we will be switching to a different branches for the main development and feature development. Is there a way to create a branch in such a way, so that we can protect it from being removed (accidentally or on purpose) unless you're a specific user (based on role or username)?
I tried to create a sample git repository in our local gitlab machine, then protected one of the branches from the option on the website, but then I was able to remove it with git push origin :branch_name. Thanks in advance!
Will the solution work on github.com?
| There are many ways to tackle this:
Make another repo that's a sand box, and give readonly access to the master one. If they delete by accident they can get the branch from the master repo. This assumes you are only using github for your repos aside the local dev repos.
Setup hooks in the repository that don't allow branches to be deleted unless you are a specific user. You can't do that on github as they won't allow arbitrary code to be executed on their servers. If you get a local repo instead, you can do this.
Setup a local gitolite install to manage branches with permissions.
| GitLab | 11,401,155 | 16 |
In Gitlab ci We have declared our variables like below
USER_NAME:
value: ""
description: "Enter Username"
File_Name:
description: "Enter the file name"
It only give a text box where We can enter the value.
Can I make a drop down select box is there any option available to make it a select box.Then we can select the value from drop down.
| GitLab 15.7 (December 2022) has finally implemented this:
Select predefined CI/CD variables values from a dropdown list
Previously, you could pre-fill CI/CD variables in the “Run pipeline” page, with a specific value.
Unfortunately, if you had multiple options for the variable’s value, you still had to manually input the option you wanted. This was an error-prone process because you could easily input an invalid value, or just mistype it.
In this release, we’ve added the ability to set a list of values which are surfaced in a drop-down list in the “Run pipeline” page.
Now you can define the exact list of values that are valid for each CI/CD variable when running a pipeline manually, greatly simplifying your workflow when using manually-triggered pipelines.
See Documentation and Issue.
| GitLab | 69,763,984 | 15 |
We are working with GitLab CI and a strange behaviour just happened. We are trying to only run a given job (e.g, lint here below) if *.py files are changed and we are in a merge request, not a simple git branch. If, for example, I am going to push a change on the Readme.MD, the pipeline's job Lint here will be executed where it should have not.
.gitlab-ci.yml configuration:
image: python:3.7
stages:
- pre-build
- test
.ci_rules:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_IID'
changes:
- tests/*.py
- tests/*/*.py
- src/*.py
- src/*/*.py
- if: $CI_COMMIT_REF_NAME == "develop"
- if: $CI_COMMIT_REF_NAME == "main"
lint:
stage: pre-build
script:
- pip install flake8
- flake8
rules:
- !reference [ .ci_rules, rules ]
# [... other jobs not relevant for the issue]
| The problem is in your job rules. Below are your numbered rules for better orientation:
1. $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_IID && changes
2. $CI_COMMIT_REF_NAME == "develop"
3. $CI_COMMIT_REF_NAME == "main"
Let's consider some examples, variables values and job evaluation result with your rules. Remember if you don't use when keyword in your rule definifon then the job evaluation needs only one rule from the rules set to trigger a job.
Create MR develop -> main with file change
1. rule ✅
2. rule ✅
3. rule ❌
---
job evaluation = ✅
Create MR develop -> main without file change
1. rule ❌
2. rule ✅
3. rule ❌
---
job evaluation = ✅
Create MR test1 -> main without file change
1. rule ❌
2. rule ❌
3. rule ❌
---
job evaluation = ❌
Push to the develop branch
1. rule ❌
2. rule ✅
3. rule ❌
---
job evaluation = ✅
Push to the main branch
1. rule ❌
2. rule ❌
3. rule ✅
---
job evaluation = ✅
Do you see it already? 🙂 I think your problem is that you have rules 2. and 3. mixed with rule 1. Therefore if you create MR without file changes, but your source branch is develop, the job rule is evaluated as true (second example). I will suggest to have rule 1. in separated job (or template). Or use rules with when keyword and control it manually for example.
| GitLab | 69,540,677 | 15 |
I have a packge script which needs to run on alpina:helm image . I have used this before but for some reason this is always giving me error as - Error: unknown command "sh" for "helm"
package:
<<: *artifacts
stage: package
image: alpine/helm
variables:
GIT_STRATEGY: none
script:
- echo $VERSION
- helm package ./keycloak --app-version=$VERSION
artifacts:
paths:
- "*.tgz"
Can anybody tell me what is the issue here I am not very sure . Helm command should be running as per my assumption but not sure why isnt it .
| As explained in the docs, the runner in gitlab is started this way
the runner starts the docker container specified in image and uses the entrypoint of this container
the runner attaches itself to the container
the runner combines before_script, script and after_script into a single script
the runner sends the combined script to the container's shell
If you take a look at the entrypoint of the alpine/helm image, you see that the entrypoint is helm and when the container starts it runs helm. The gitlab runner expects no entrypoint or that the entrypoint is set to start a shell so you get the Error: unknown command "sh" for "helm" as there is no running shell.
With overriding the entrypoint we make sure the runner finds a shell in the container which can execute the script.
package:
stage: package
image:
name: alpine/helm
entrypoint: [""]
variables:
GIT_STRATEGY: none
script:
- echo $VERSION
- helm package ./keycloak --app-version=$VERSION
artifacts:
paths:
- "*.tgz"
EDIT:
By reading the docs again I changed the entrypoint to an empty entrypoint for docker 17.06 and later (entrypoint: [""]) as this is more concise.
| GitLab | 67,289,837 | 15 |
I'm looking for the right way to set up a variable when I launch a job manually.
I tried :
stages:
- test
my_job:
stage: test
script:
- echo "HEY"
variables:
FIRST_VARIABLE: "my_variable"
SECOND_VARIABLE:
value: "a"
description: "b"
when: manual
I want my SECOND_VARIABLE to appear into the following VARIABLES field, with a pre-field value : a.
Unfortunatly, I got some error trying "variables config should be a hash of key value pairs" error.
I tried with the gitlab documentation (cf variables), but it fails.
Can you help me to solve this problem ?
| This is currently not implemented, it is supported on the New Pipeline Form but not for manual steps - https://gitlab.com/gitlab-org/gitlab/-/issues/30101 is a good resource, where you can easily track the progress.
There are tickets in the backlog like https://gitlab.com/gitlab-org/gitlab/-/issues/22629 - but as said currently this is not possible to be prefilled.
| GitLab | 66,207,501 | 15 |
I have a scheduled pipeline that copies some data from one server to another once a day.
The pipeline works fine on all branches but doesn't start if I select master branch (default branch) as the target branch.
I have tried on an exact copy of master and it worked fine.
I though it could be because master is protected but I tried on a protected copy of master and it worked.
I'm really not sure what's going on. When I click the "play" button next to the scheduled pipeline and it says that the job was successfully scheduled, but I cannot see any job in the job list.
Here some details on the .gitlab-ci.yml
stages:
- copy_data
- linting
- test
- deploy
lint:
needs: []
stage: linting
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH'
changes:
- "my_project/**/*.py"
script:
- ...
test:
stage: test
script:
- ...
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH'
copy_database:on-schedule:
stage: copy_data
needs: []
only:
- schedules
- $COPY_DB # this is set in the pipeline menu on gitlab
script:
- ...
timeout: 3h
| I finally figured out the problem! The issue is that gitlab was saying Successfully scheduled a pipeline to run. Go to the Pipelines page for details. while in reality there was an error.
To debug it I used the trick described here that is to run a manual pipeline and set CI_PIPELINE_SOURCE = "schedule". Running the pipeline in this way returned the error message and I was able to fix the issue.
If you are wondering what the error was, here is some more detail.
I had two pipelines optionally running on the master branch:
prepare_release:
stage: prepare_release
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_COMMIT_TAG
when: never
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
script:
- ...
create_release:
image: registry.gitlab.com/gitlab-org/release-cli:latest
stage: release
needs:
- job: prepare_release
artifacts: true
rules:
// HERE THERE SHOULD BE A RULE TO PREVENT THIS FROM RUNNING ON SCHEDULE
// - if: $CI_PIPELINE_SOURCE == "schedule"
// when: never
- if: $CI_COMMIT_TAG
when: never
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script:
- ...
The second pipeline did not have a
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
And therefore tried running on the schedule. However since it needs the previous one and that wasn’t created, it errors.
Mi mistake was to assume that the "needs" would take into account this rule from the parent job.
| GitLab | 65,816,737 | 15 |
Git command itself supports the Signed-off-by: Person's name <persons@email> line.
GitHub adds Co-authored-by: line, which then shows both the committer and the referenced person as commit authors in the UI. (See Q: GitHub co-authored-by with private noreply address for discussion how to avoid exposing email addresses.)
Futhermore, GitHub and GitLab each recognize a set of keywords to close issues when a commit is merged.
Is the list of Git magic keywords above complete? Is there a standardization process for adding these lines and keywords? Are these defined to be case insensitive?
| From the OP:
The git command itself supports the Signed-off-by: Person's name <persons@email> line.
Starting with Git 2.32 (Q2 2021), the git command itself supports... any trailer you want!
"git commit"(man) learned --trailer <key>[=<value>] option; together with the interpret-trailers command, this will make it easier to support custom trailers.
See commit 2daae3d (23 Mar 2021) by ZheNing Hu (adlternative).
(Merged by Junio C Hamano -- gitster -- in commit 68e15e0, 07 Apr 2021)
commit: add --trailer option
Signed-off-by: ZheNing Hu
Historically, Git has supported the 'Signed-off-by' commit trailer using the '--signoff' and the '-s' option from the command line.
But users may need to provide other trailer information from the command line such as "Helped-by", "Reported-by", "Mentored-by",
Now implement a new --trailer <token>[(=|:)<value>] option to pass other trailers to interpret-trailers and insert them into commit messages.
git commit now includes in its man page:
--trailer <token>[(=|:)<value>]
Specify a (<token>, <value>) pair that should be applied as a
trailer.
For instance:
git commit --trailer "Signed-off-by:C O Mitter <[email protected]>" \
--trailer "Helped-by:C O Mitter <[email protected]>"
That will add the "Signed-off-by" trailer and the "Helped-by" trailer to the commit message.
The trailer.* configuration variables
(git interpret-trailers) can be used to define if
a duplicated trailer is omitted, where in the run of trailers
each trailer would appear, and other details.
Regarding that trailer.xxx configuration, consider an initial commit that you want to amend with additional trailers:
Signed-off-by: C O Mitter <[email protected]>
Signed-off-by: C1 E1
Reported-by: C3 E3
Mentored-by: C4 E4
Helped-by: C3 E3
A trailer.ifexists="replace" config would, if you amend it by adding the same Reported-by, keep the message unchanged:
git -c trailer.ifexists="replace" \
commit --trailer "Mentored-by: C4 E4" \
--trailer "Helped-by: C3 E3" \
--amend
But if you amend the same commit with trailer.ifexists="add" would means:
Signed-off-by: C O Mitter <[email protected]>
Signed-off-by: C1 E1
Helped-by: C2 E2
Reported-by: C3 E3
Mentored-by: C4 E4
Reported-by: C3 E3 <<<< added twice
Mentored-by: C4 E4 <<<< added twice
And using trailer.ifexists="addIfDifferent"
git -c trailer.ifexists="addIfDifferent" \
commit --trailer "Reported-by: C3 E3" \
--trailer "Mentored-by: C5 E5" \
--amend
And you get:
Signed-off-by: C O Mitter <[email protected]>
Signed-off-by: C1 E1
Helped-by: C2 E2
Reported-by: C3 E3
Mentored-by: C4 E4
Mentored-by: C5 E5 <<<< Only C5 E5 is added
And, still With Git 2.32 (Q2 2021), the way the command line specified by the trailer.<token>.command configuration variable receives the end-user supplied value was both error prone and misleading.
An alternative to achieve the same goal in a safer and more intuitive way has been added, as the trailer.<token>.cmd configuration variable, to replace it.
See commit c364b7e, commit 57dcb65 (03 May 2021) by ZheNing Hu (adlternative).
(Merged by Junio C Hamano -- gitster -- in commit 2cd6ce2, 11 May 2021)
trailer: add new .cmd config option
Helped-by: Junio C Hamano
Helped-by: Christian Couder
Signed-off-by: ZheNing Hu
The trailer.<token>.command configuration variable specifies a command (run via the shell, so it does not have to be a single name or path to the command, but can be a shell script), and the first occurrence of substring $ARG is replaced with the value given to the interpret-trailer command for the token in a '--trailer <token>=<value>' argument.
This has three downsides:
The use of $ARG in the mechanism misleads the users that
the value is passed in the shell variable, and tempt them to use $ARG more than once, but that would not work, as the second and subsequent $ARG are not replaced.
Because $ARG is textually replaced without regard to the
shell language syntax, even '$ARG' (inside a single-quote pair), which a user would expect to stay intact, would be replaced, and worse, if the value had an unmatched single quote (imagine a name like "O'Connor", substituted into NAME='$ARG' to make it NAME='O'Connor'), it would result in a broken command that is not syntactically correct (or worse).
The first occurrence of substring $ARG will be replaced with the empty string, in the command when the command is first called to add a trailer with the specified <token>.
This is a bad design, the nature of automatic execution causes it to add a trailer that we don't expect.
Introduce a new trailer.<token>.cmd configuration that takes higher precedence to deprecate and eventually remove trailer.<token>.command, which passes the value as an argument to the command.
Instead of "$ARG", users can refer to the value as positional argument, $1, in their scripts.
At the same time, in order to allow git interpret-trailers(man) to better simulate the behavior of git command -s, 'trailer.<token>.cmd' will not automatically execute.
git interpret-trailers now includes in its man page:
This option behaves in the same way as 'trailer.<token>.cmd', except
that it doesn't pass anything as argument to the specified command.
Instead the first occurrence of substring $ARG is replaced by the
value that would be passed as argument.
The 'trailer.<token>.command' option has been deprecated in favor of
'trailer.<token>.cmd' due to the fact that $ARG in the user's command is
only replaced once and that the original way of replacing $ARG is not safe.
When both 'trailer.<token>.cmd' and 'trailer.<token>.command' are given
for the same <token>, 'trailer.<token>.cmd' is used and
'trailer.<token>.command' is ignored.
trailer.<token>.cmd
git interpret-trailers now includes in its man page:
of these arguments, if any, will be passed to the command as its
first argument.
This way the command can produce a computed
from the <value> passed in the '--trailer <token>=<value>' argument.
git interpret-trailers now includes in its man page:
Configure a 'help' trailer with a cmd use a script glog-find-author
which search specified author identity from git log in git repository
and show how it works:
$ cat ~/bin/glog-find-author
#!/bin/sh
test -n "$1" && git log --author="$1" --pretty="%an <%ae>" -1 || true
$ git config trailer.help.key "Helped-by: "
$ git config trailer.help.ifExists "addIfDifferentNeighbor"
$ git config trailer.help.cmd "~/bin/glog-find-author"
$ git interpret-trailers --trailer="help:Junio" --trailer="help:Couder" <<EOF
> subject
>
> message
>
> EOF
subject
message
Helped-by: Junio C Hamano <[email protected]>
Helped-by: Christian Couder <[email protected]>
Configure a 'ref' trailer with a cmd use a script glog-grep
to grep last relevant commit from git log in the git repository
and show how it works:
$ cat ~/bin/glog-grep
#!/bin/sh
test -n "$1" && git log --grep "$1" --pretty=reference -1 || true
$ git config trailer.ref.key "Reference-to: "
$ git config trailer.ref.ifExists "replace"
$ git config trailer.ref.cmd "~/bin/glog-grep"
$ git interpret-trailers --trailer="ref:Add copyright notices." <<EOF
> subject
>
> message
>
> EOF
subject
message
Reference-to: 8bc9a0c769 (Add copyright notices., 2005-04-07)
| GitLab | 58,525,836 | 15 |
So after googling a little bit (which is polluted by people having trouble with Pull Secrets) I am posting this here — and to GCP Support (will update as I hear).
I created a Cluster from GitLab Kubernetes integration (docs: https://about.gitlab.com/solutions/kubernetes) within the same project as my GCR registry / images.
When I add a new service / deployment to this Cluster using Kubectl (which relies on a private image within the GCR Registry in this project) the pods in the GitLab created cluster fail to pull from GCR with: ErrImagePull.
To be clear — I am NOT pulling from a GitLab private registry, I am attempting to pull from a GCR Registry within the same project as the GKE cluster created from GitLab (which should not require a Pull Secret).
Other Clusters (created from GCP console) within this project can properly access the same image so my thinking is that there is some difference between Clusters created via an API (in this case from GitLab) vs Clusters created from the GCP console.
I am hoping someone has run into this in the past — or can explain the differences in the Service Accounts etc that could be causing the problem.
I am going to attempt to create a service account and manually grant it Project Viewer role to see if that solves the problem.
Update: manually configured Service Account did not solve issue.
Note: I am trying to pull an image into the Cluster NOT into a GitLab Runner that is running on the Cluster. Ie. I want a separate Service / Deployment to be running along side my GitLab infrastructure.
| TL;DR — Clusters created by GitLab-Ci Kubernetes Integration will not be able to pull an image from a GCR Registry in the same project as the container images — without modifying the Node(s) permissions (scopes).
While you CAN manually modify the permissions on an Individual Node machine(s) to grant the Application Default Credentials (see: https://developers.google.com/identity/protocols/application-default-credentials) the proper scopes in real time — doing it this way would mean that if your node is re-created at some point in the future it WOULD NOT have your modified scopes and things would break.
Instead of modifying the permissions manually — create a new Node pool that has the proper Scope(s) to access your required GCP services.
Here are some resources I used for reference:
https://medium.com/google-cloud/updating-google-container-engine-vm-scopes-with-zero-downtime-50bff87e5f80
https://adilsoncarvalho.com/changing-a-running-kubernetes-cluster-permissions-a-k-a-scopes-3e90a3b95636
Creating a properly Scoped Node Pool Generally looks like this
gcloud container node-pools create [new pool name] \
--cluster [cluster name] \
--machine-type [your desired machine type] \
--num-nodes [same-number-nodes] \
--scopes [your new set of scopes]
If you aren't sure what the names of your required Scopes are — You can see a full list of Scopes AND Scope Aliases over here: https://cloud.google.com/sdk/gcloud/reference/container/node-pools/create
For me I did gke-default (same as my other cluster) and sql-admin. The reason for this being that I need to be able to access an SQL Database in Cloud SQL during part of my build and I don't want to have to connect to a pubic IP to do that.
gke-default Scopes (for reference)
https://www.googleapis.com/auth/devstorage.read_only (allows you to pull)
https://www.googleapis.com/auth/logging.write
https://www.googleapis.com/auth/monitoring
https://www.googleapis.com/auth/service.management.readonly
https://www.googleapis.com/auth/servicecontrol
https://www.googleapis.com/auth/trace.append
Contrast the above with more locked down permissions from a GitLab-Ci created cluster ( ONLY these two: https://www.googleapis.com/auth/logging.write, https://www.googleapis.com/auth/monitoring):
Obviosuly configuring your cluster to ONLY the minimum permissions needed is for sure the way to go here. Once you figure out what that is and create your new properly scoped Node Pool...
List your nodes with:
kubectl get nodes
The one you just created (most recent) is has the new settings while the older option is the default gitlab cluster that can pull from the GCR.
Then:
kubectl cordon [your-node-name-here]
After that you want to drain:
kubectl drain [your-node-name-here] --force
I ran into issues where the fact that I had a GitLab Runner installed meant that I couldn't drain the pods normally due to the local data / daemon set that was used to control it.
For that reason once I cordon'd my Node I just deleted the node from Kubectl (not sure if this will cause problems — but it was fine for me). Once your node is deleted you need to delete the 'default-pool' node pool created by GitLab.
List your node-pools:
gcloud container node-pools list --cluster [CLUSTER_NAME]
See the old scopes created by gitlab:
gcloud container node-pools describe default-pool \
--cluster [CLUSTER_NAME]
Check to see if you have the correct new scopes (that you just added):
gcloud container node-pools describe [NEW_POOL_NAME] \
--cluster [CLUSTER_NAME]
If your new Node Pool has the right scopes your deployments can now delete the default pool with:
gcloud container node-pools delete default-pool \
--cluster <YOUR_CLUSTER_NAME> --zone <YOUR_ZONE>
In my personal case I am still trying to figure out how to allow access to the private network (ie. get to Cloud SQL via private IP) but I can pull my images now so I am half way there.
I think that's it — hope it saved you a few minutes!
| GitLab | 54,043,495 | 15 |
I'm trying to run my Gitlab CI locally using Gitlab-runner and docker before committing to make sure they work okay. But I'm having some strange issues!
Unfortunately I have no choice but to use windows (I've had success in the past on Linux).
Every time I run a job in powershell:
C:/Gitlab-runner/gitlab-runner exec docker npm
I get an error:
Job failed (system failure): Error response from daemon: invalid volume specification: '/host_mnt/c/builds/project-0/Users/Lewsmith/api:C:/Users/Lewsmith/api:ro' (executor_docker.go:921:0s)
I've tried setting docker volumes (nemerous combinations) and builds-dir:
C:/Gitlab-runner/gitlab-runner exec docker --builds-dir /builds --docker-privileged --docker-volumes "/builds:C:/Gitlab-runner/builds" npm
That fails with Error response from daemon: invalid mode: /Gitlab-runner/builds because of the colon after the C..
Can anyone point me in the right direction as I'm stumped?
Using gitlab-runner version 11.5.0
| Docker is not fully supported by GitLab Runner on Windows yet.
The workaround is to use Windows Subsystem for Linux and install gitlab-runner there:
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash
sudo apt-get install gitlab-runner
gitlab-runner exec docker build
| GitLab | 53,472,481 | 15 |
I have a job in my .gitlab-ci.yml file which does an npm install like so:
test:
image: node:10
script:
- npm install
- npm test
The problem is that I'm referencing a private GitLab repo in my package.json:
"dependencies": {
"internal-dep": "git+https://gitlab.com/Company/internal-dep.git",
...
The npm install command works locally, since I'm already authed against GitLab, but fails on GitLab CI. How do I get internal-dep to resolve successfully on GitLab CI?
| There are two approaches I've found that allow Git to auth successfully against GitLab during the npm install step (which uses Git under the hood to access this dependency).
First approach, as shown in this .gitlab-ci.yml job:
test:
image: node:10
script:
- echo -e "machine gitlab.com\nlogin gitlab-ci-token\npassword ${CI_JOB_TOKEN}" > ~/.netrc
- npm install
- npm test
Second approach, which also seems to work:
test:
image: node:10
script:
- git config --global url."https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/".insteadOf https://gitlab.com/
- npm install
- npm test
| GitLab | 52,784,182 | 15 |
In my gitlab-ci.yml file, I have defined 3 stages, and the 2nd and 3rd stages have 3 jobs each, resulting in the following structure:
The 1st and 2nd stage works as I intended, however, for the 3rd stage what I'd actually like to have is something like this (the image is a mockup of course), i.e. "parallel sequences" of jobs if you will:
That is, I want "deploy-b" to start if "build-b" is done, and not waiting for the other build tasks to complete.
Is that possible with GitLab pipelines? (Apart from the obvious solution of defining just 2 stages, the second being "Build-and-Deploy", where I just "merge" the script steps of the current build-* and deploy-* jobs.)
| This feature was added in the new GitLab release (v12.2)
| GitLab | 52,382,718 | 15 |
I have a C++ project that is compiled and packaged for multiple OS (Linux, Windows, MacOS) as well as multiple CPU architectures (i386, x86_64, arm, Aarch64)
For this I'm using Jenkins to grab the source code and run the build script in parallel on each system. It's a simple working solution, since my build script deals with the system differences.
Now I'm looking into Gitlab CI/CD, and it has many things I find appealing ( being able to keep the build script as part of the repository, very well integrated with the git repo and ticketing system, natural use of Docker containers, etc), but I cannot find any way to run the same pipeline in multiple architectures/systems parallel to each other.
So, say that my build script is:
build:
stage: build
script:
- uname -m > arch.txt
artifacts:
paths:
- arch.txt
How can I tell Gitlab that I want to run this job in multiple runners/Docker containers/systems at the same time? All the documentation I've read so far deals with running multiple tests on one build, integrating multiple projects or deploying in different environments depending on branches. Nothing I've read so far tries to do many separate builds, test and package them individually and report on their independent results. Is this feasible on Gitlab CI/CD?
| GitLab uses "runners" to execute CI jobs. Runners are installed wherever you want to run a CI job, so if you want to run on multiple architectures then you will need to install runners on systems for each architecture. Runner install documentation can be found here:
https://docs.gitlab.com/runner/install/index.html
For Linux-based jobs it is common to use Docker for job execution - this doesn't give architectural flexibility, but it does allow you to test on different flavors and with different software using containerisation. For other architectures you may need to install runners yourself, or use other peoples shared runners.
While you are installing the runner software there are some keys steps:
you have the opportunity to link each runner to your GitLab project, which means it will show up in the runners list under Project > Settings > CI/CD.
you will have the opportunity to assign "tags" to the runners. Tags can be used to help identify a runner or group of runners by an arbitrary name (e.g. you could add "Windows x86_64" as a tag, or "Windows" and "x86_64" tags). These tags can be used in jobs to select a runner.
Once you have your runners installed you can get editing your .gitlab-ci.yml file.
GitLab CI files are broken up into "stages". Jobs in each stage can run in parallel. Stage names are defined at the top of the file.
stages:
- build
- deploy
Each CI job can be attached to a stage by using the stage: entry:
build job:
stage: build
script:
- echo "I am a build stage job"
In your case you will need to create multiple jobs for each architecture you want to build for. Attaching these to the same stage will allow them to run in parallel.
To control where each job runs you have two main mechanisms:
Tags - tags allow you to pin a job to a runner tag. You can specify multiple tags using the tags: entry which forms an AND list (e.g. win tag AND x86_64 tag). When that job runs GitLab will find a runner that has all the required tags, and run the job there.
Image - When running on Docker / Kubernetes you can specify a docker image to use for the runner. To use a docker image you first need to specify a runner that can run docker images (e.g. a docker-in-docker or kubernetes runner), which might, for example, be tagged with docker or kubernetes. Then you use the image: entry to specify the docker image.
Here's an example showing both tags and images:
build win x86_64:
stage: build
tags:
- win
- x86_64
script:
- echo "I am a build stage job for win x86_64"
build win 32:
stage: build
tags:
- win
- 32-bit
script:
- echo "I am a build stage job for win 32"
build debian:
stage: build
tags:
- docker
image: debian:stretch
script:
- echo "I am a build stage job for debian, running on docker using debian:stretch image"
There is currently no support for dynamic jobs, or running one job on multiple runners / architectures, so this involves a bit of manual effort. On the positive side it makes GitLab CI files easy to read, and easy to see what will run during CI execution.
| GitLab | 52,031,860 | 15 |
I am trying to work simultaneously on more than one (two or three) GitLab (or even GitHub) projects on a single development machine. Because upon configuration the IDEs and the git service has the data of my primary user when I try to checkout or clone another project with a different username / password the system says either project is not found or I do not have permissions to do that.
How can I configure and use more than one git user on a single development machine?
| By default, git is using a system-wide configuration file or the one stored at top of your home directory.
But you can also set a file .git/config inside each repository, either by editing manually or using git config. Inside, you may specify the following sections :
[user]
name = Your name
email = [email protected]
…
[credential "<your_project_hoster_url>"]
username = <username to log in with>
You can check git config in general or git credentials in particular for more information about it.
| GitLab | 50,354,412 | 15 |
I want to understand the difference between projects and subgroups in GitLab.
Please help me on understanding the above.
| Project
A project manages one git repository and adds an issue tracker, a wiki, etc:
See: https://docs.gitlab.com/ee/user/project/index.html#doc-nav
Groups
Groups can be used to combine several projects under one topic. Examples:
You could put all your JavaScript projects in a group called "js"
You could create one group for each of your developer teams; then if somebody new joins a team, you can just add them to the group instead of having to grant developer access for every project.
Groups can be referred in issues or commit discussions.
See: https://docs.gitlab.com/ee/user/group/index.html#doc-nav
Different groups may have different permissions
Subgroups
Subgroups are only available in GitLab 9 and above; they allow you to create additional groups inside of groups, e.g. "js/frontend"; this is useful if you are working on a large project with several sub-projects. See the official documentation for some examples:
https://docs.gitlab.com/ee/user/group/subgroups/index.html
| GitLab | 50,272,566 | 15 |
I have a secret var :
But when I do - echo %MySecretVar%, runner displays foo only
How can i escape special chars like ! in Gitlab Secret Vars ?
| I had the same problems with Gitlab, job running on windows, but I assume it will reproduce on Linux as well, because it seems Gitlab parsing issue or relay weird escaping.
So I have set environment variable
APPPOOL_PWD: 'blabla!foo$bar'
and output of echo %APPPOOL_PWD% or echo $APPPOOL_PWD was 'blabla'
The Gitlab seems to be was eating out the exclamation mark sign ! and dollar sign $. To avoid it as proposed in comment for exclamation mark I have used ^^ and for dollar sign I have used $$ as proposed in the Gitlab variables documentation.
So following variable works well:
APPPOOL_PWD: 'blabla^^!foo$$bar'
and output of the echo command in this case would be 'blabla!foo$bar'.
| GitLab | 48,870,664 | 15 |
For testing a command line tool against a Gitlab instance in Docker, I would like to login to Gitlab using username and password and grab the created session to authenticate my API requests.
Therefore I do the following:
curl the user login page with curl -i http://localhost:8080/users/sign_in -s
get me the _gitlab_session from the headers
get me the authenticity_token from the login form
send a second curl request with
curl 'http://localhost:8080/users/sign_in' \
-H "_gitlab_session=${cookie}" \
-H 'Origin: http://localhost:8080' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' \
-H 'Referer: http://localhost:8080/users/sign_in' \
-H 'Connection: keep-alive' \
--data-urlencode "authenticity_token=${token}" \
--data-urlencode "user[login]=root" \
--data-urlencode "user[password]=12341234" \
--data-urlencode "user[remember_me]=0"
But instead of a valid user login, I get a
422 - The change you requested was rejected.
And in the logfiles, I see
==> gitlab-rails/production.log <==
Started POST "/users/sign_in" for 172.17.0.1 at 2017-12-23 00:22:16 +0000
Processing by SessionsController#create as HTML
Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"login"=>"root", "password"=>"[FILTERED]", "remember_me"=>"0"}}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 125ms (ActiveRecord: 7.8ms)
==> gitlab-rails/production_json.log <==
{"method":"POST","path":"/users/sign_in","format":"html","controller":"SessionsController",
"action":"create","status":422,"error":"
ActionController::InvalidAuthenticityToken:ActionController::InvalidAuthenticityToken",
"duration":126.29,"view":0.0,"db":7.78,"time":"2017-12-23T00:22:16.039Z",
"params":{"authenticity_token":"[FILTERED]","user":{"login":"root","password":"
[FILTERED]","remember_me":"0"}},"remote_ip":"172.17.0.1",
"user_id":1,"username":"root"}
==> gitlab-rails/production.log <==
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
lib/gitlab/middleware/multipart.rb:93:in `call'
lib/gitlab/request_profiler/middleware.rb:14:in `call'
lib/gitlab/middleware/go.rb:18:in `call'
lib/gitlab/etag_caching/middleware.rb:11:in `call'
lib/gitlab/middleware/read_only.rb:31:in `call'
lib/gitlab/request_context.rb:18:in `call'
lib/gitlab/metrics/requests_rack_middleware.rb:27:in `call'
I assume that I forgot to pass a necessary ingredient in the second request - but I can't figure out, which one.
| With some helpful tips by other answers and comments, I finally came up with this solution:
gitlab_host="http://localhost:8080"
gitlab_user="root"
gitlab_password="12341234"
# curl for the login page to get a session cookie and the sources with the auth tokens
body_header=$(curl -c cookies.txt -i "${gitlab_host}/users/sign_in" -s)
# grep the auth token for the user login for
# not sure whether another token on the page will work, too - there are 3 of them
csrf_token=$(echo $body_header | perl -ne 'print "$1\n" if /new_user.*?authenticity_token"[[:blank:]]value="(.+?)"/' | sed -n 1p)
# send login credentials with curl, using cookies and token from previous request
curl -b cookies.txt -c cookies.txt -i "${gitlab_host}/users/sign_in" \
--data "user[login]=${gitlab_user}&user[password]=${gitlab_password}" \
--data-urlencode "authenticity_token=${csrf_token}"
# send curl GET request to personal access token page to get auth token
body_header=$(curl -H 'user-agent: curl' -b cookies.txt -i "${gitlab_host}/profile/personal_access_tokens" -s)
csrf_token=$(echo $body_header | perl -ne 'print "$1\n" if /authenticity_token"[[:blank:]]value="(.+?)"/' | sed -n 1p)
# curl POST request to send the "generate personal access token form"
# the response will be a redirect, so we have to follow using `-L`
body_header=$(curl -L -b cookies.txt "${gitlab_host}/profile/personal_access_tokens" \
--data-urlencode "authenticity_token=${csrf_token}" \
--data 'personal_access_token[name]=golab-generated&personal_access_token[expires_at]=&personal_access_token[scopes][]=api')
# Scrape the personal access token from the response HTML
personal_access_token=$(echo $body_header | perl -ne 'print "$1\n" if /created-personal-access-token"[[:blank:]]value="(.+?)"/' | sed -n 1p)
According to the GitLab API documentation you can now use the session cookie to authenticate API requests:
curl --header "Private-Token: ${personal_access_token}" https://gitlab.example.com/api/v4/projects
Some hints:
I first got confused with the curl -c file (which reads cookies from the headers and writes them to the file) vs. the curl -b file (which uses the cookies in the file and sends them with the request)
Unfortunately I did not find a regex that worked with sed so I have to use perl here.
Using the developer console in Chrome and copying a POST request as curl command was very helpful: https://www.alexkras.com/copy-any-api-call-as-curl-request-with-chrome-developer-tools/
| GitLab | 47,948,887 | 15 |
Let's say I have these stages defined in .gitlab-ci.yml:
stages:
- build
- analysis
- tests
- deploy
- post-deploy
Since analysis takes a lot of time and I don't really care about the result (I also have allow_failure: true set) - is it possible to somehow define to start analysis and then immediately launch the next stage tests?
I didn't find any reference to similar topic on official docs.
EDIT:
The main idea is that all other stages can be run as if the analysis didn't even exist. If i put analysis to same stage as tests, then both analysis and tests will run at the same time, however deploy won't be launched until both of them finish. This is no good. I want tests to finish and then launch deploy, after deploy finishes I want to launch post-deploy. I really don't care about analysis result, I simply want to trigger it and continue with the deployment.
| Since v12.8, you can use needs: [] to start jobs start immediately. Docs: https://docs.gitlab.com/ee/ci/yaml/#needs
| GitLab | 47,286,456 | 15 |
I've created a remote branch whose name starts with a hashtag mark and I've quickly learnt it's a bad idea as # is considered as a comment mark by git.
Therefore, I would like to delete that branch now but I can't find a proper way to do so… I've tried :
git push origin --delete <#branch_name>
git push origin --delete -- <#branch_name>
But git always returns this error message
fatal: --delete doesn't make sense without any refs.
So how can I walk around that issue ?
| Escape the #:
git push origin --delete \#branch_name
↑
| GitLab | 46,402,440 | 15 |
How do I use PowerShell commands/scripts with Gitlab CI in a .gitlab-ci.yml file which is used to deploy to gitlab pages?
I am trying to execute the build.ps1 file from .gitlab-ci.yml, but when it reaches the build.ps1 line, it gives an error saying
/bin/bash: line 5: .build.ps1: command not found
I am trying to use the PowerShell script to convert a file in my repo and have the converted file deployed to gitlab pages using .gitlab-ci.yml
Here is my code:
.gitlab.yml
pages:
stage: deploy
script:
- mkdir .public
- .\build.ps1
- cp -r * .public
- mv .public public
artifacts:
paths:
- public
only:
- master
| I have been able to figure out a solution to my own question.
Solution
To Run PowerShell Command/Script from a .gitlab-ci.yml file on a gitlab.com using the Gitlab CI, you need to make sure that the contents of your .gitlab-ci.yml file is as shown below.
Note: The .gitlab-ci.yml below works without having to install a Gitlab Runner on your own machine and has been tested on the http://gitlab.com website.
image: philippheuer/docker-gitlab-powershell
pages:
stage: deploy
script:
- mkdir .public
# run PowerShell Script
- powershell -File build.ps1
# run PowerShell Command
- powershell -Command "Get-Date"
- cp -r * .public
- mv .public public
artifacts:
paths:
- public
only:
- master
| GitLab | 44,319,313 | 15 |
I'm starting phantomjs with specific arguments as part of my job.
This is running on a custom gitlab/gitlab-ci server, I'm currently not using containers, I guess that would simplify that.
I'm starting phantomjs like this:
- "timeout 300 phantomjs --ssl-protocol=any --ignore-ssl-errors=true vendor/jcalderonzumba/gastonjs/src/Client/main.js 8510 1024 768 2>&1 >> /tmp/gastonjs.log &"
Then I'm running my behat tests, and then I'm stopping that process again:
- "pkill -f 'src/Client/main.js' || true"
The problem is when a behat test fails, then it doesn't execute the pkill and the test-run is stuck waiting on phantomjs to finish. I already added the timeout 300 but that means I'm still currently waiting 2min or so after a fail and it will eventually stop it while test are still running when they get slow enough.
I haven't found a way to run some kind of post-run/cleanup command that also runs in case of fails.
Is there a better way to do this? Can I start phantomjs in a way that gitlab-ci doesn't care that it is still running? nohup maybe?
| TL;DR; - spawn the process in a new thread with & but then you have to make sure the process is killed in successfull and failure builds.
i use this (with comments):
'E2E tests':
before_script:
- yarn install --force >/dev/null
# if there is already an instance running kill it - this is ok in my case - as this is not run very often
- /bin/bash -c '/usr/bin/killall -q lite-server; exit 0'
- export DOCKERHOST=$(ifconfig | grep -E "([0-9]{1,3}\\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d ':' | head -n1)
- export E2E_BASE_URL="http://$DOCKERHOST:8000/#."
# start the lite-server in a new process
- lite-server -c bs-config.js >/dev/null &
script:
# run the tests
- node_modules/.bin/protractor ./protractor.conf.js --seleniumAddress="http://localhost:4444/wd/hub" --baseUrl="http://$DOCKERHOST:8000" --browser chrome
# on a successfull run - kill lite server
- killall lite-server >/dev/null
after_script:
# when a test fails - try to kill it in the after_script. this looks rather complicated, but it makes sure your builds dont fail when the tests succeedes and the lite-server is already killed. to have a successfull build we ensure a non-error return code (exit 0)
- /bin/bash -c '/usr/bin/killall -q lite-server; exit 0'
stage: test
dependencies:
- Build
tags:
- selenium
https://gist.github.com/rufinus/9ee8f04fc1f9248eeb0c73ad5360a006#file-gitlab-ci-yml-L7
| GitLab | 44,112,605 | 15 |
This is how I do some linter test (eslint).
linter:
image: ubuntu:16.04
stage: test
tags:
- testing
before_script:
- apt-get update -y
- apt-get install nodejs-legacy -yqq
- apt-get install curl -yqq
- curl https://install.meteor.com/ | sh
- meteor npm install eslint eslint-plugin-react
script:
- ./node_modules/.bin/eslint --ext .js --ext .jsx .
But with this every test will have to install the packages to the ubuntu image, which takes time.
So I thought to build a image with exact this. I came up with this Dockerfile:
FROM ubuntu:16.04
RUN apt-get update -y
RUN apt-get install nodejs-legacy -yqq
RUN apt-get install curl -yqq
RUN apt-get clean && apt-get autoclean && apt-get autoremove
RUN curl https://install.meteor.com/ | sh
Then I do
$ docker build -t linter-testing:latest .
and this yml file:
linter:
image: linter-testing:latest
stage: test
tags:
- testing
before_script:
- meteor npm install eslint eslint-plugin-react
script:
- ./node_modules/.bin/eslint --ext .js --ext .jsx .
But it fails with this error:
ERROR: Job failed: Error response from daemon: repository linter-testing not found: does not exist or no pull access
So why is this image not existing, althoug docker images shows me exact that image...
| You need to edit your config.toml file which is in /etc/gitlab-runner on your runner machine with the following
[runners.docker]
pull_policy = "if-not-present"
See related issue here.
| GitLab | 43,481,618 | 15 |
I have a directory which is generated during a build and it should not be deleted in the next builds. I tried to keep the directory using cache in .gitlab-ci.yml:
cache:
key: "$CI_BUILD_REF_NAME"
untracked: true
paths:
- target_directory/
build-runner1:
stage: build
script:
- ./build-platform.sh target_directory
In the first build a cache.zip is generated but for the next builds the target_directory is deleted and the cache.zip is extracted which takes a very long time. Here is a log of the the second build:
Running with gitlab-ci-multi-runner 1.11.
on Runner1
Using Shell executor...
Running on Runner1...
Fetching changes...
Removing target_directory/
HEAD is now at xxxxx Update .gitlab-ci.yml
From xxxx
Checking out xxx as master...
Skipping Git submodules setup
Checking cache for master...
Successfully extracted cache
Is there a way that gitlab runner not remove the directory in the first place?
| What you need is to use a job artifacts:
Artifacts is a list of files and directories which are attached to a
job after it completes successfully.
.gitlab-ci.yml file:
your job:
before_script:
- do something
script:
- do another thing
- do something to generate your zip file (example: myFiles.zip)
artifacts:
paths:
- myFiles.zip
After a job finishes, if you visit the job's specific page, you can see that there is a button for downloading the artifacts archive.
Note
If you need to pass artifacts between different jobs, you need to use dependencies.
Gitlab has a good documentation about that if you really have this need http://docs.gitlab.com/ce/ci/yaml/README.html#dependencies
| GitLab | 42,948,062 | 15 |
is it possible to exclude a directory from displaying a diff of merge request in GitLab?
We started to version the bower_components folder (1 - to speed up app build, 2 - because bower has no .lock mechanism), but it makes trouble when doing code review - many changed files appear inside bower_components which makes the diff harder to read.
Thanks in advance
| Since gitlab 8.8, gitlab support the .gitattributes.
So if your project does not have .gitattributes add it,
and to exclude files for diff, append:
*.<whatever> -diff
and to exclude directories from a diff:
<mydir> -diff
| GitLab | 41,116,855 | 15 |
I have the following configuration as .gitlab-ci.yml
but I found out after successfully pass build stage (which
would create a virtualenv called venv), it seems that
in test stage you would get a brand new environment(there's
no venv directory at all). So I wonder should I put setup
script in before_script therefor it would run in each phase(build/test/deploy). Is it a right way to do it ?
before_script:
- uname -r
types:
- build
- test
- deploy
job_install:
type: build
script:
- apt-get update
- apt-get install -y libncurses5-dev
- apt-get install -y libxml2-dev libxslt1-dev
- apt-get install -y python-dev libffi-dev libssl-dev
- apt-get install -y python-virtualenv
- apt-get install -y python-pip
- virtualenv --no-site-packages venv
- source venv/bin/activate
- pip install -q -r requirements.txt
- ls -al
only:
- master
job_test:
type: test
script:
- ls -al
- source venv/bin/activate
- cp crawler/settings.sample.py crawler/settings.py
- cd crawler
- py.test -s -v
only:
- master
adasd
| Gitlab CI jobs supposed to be independent, because they could run on different runners. It is not issue. There two ways to pass files between stages:
The right way. Using artefacts.
The wrong way. Using cache. With cache key "hack". Still need same runner.
So yes, supposed by gitlab way to have everything your job depends on in before script.
Artifacts example:
artifacts:
when: on_success
expire_in: 1 mos
paths:
- some_project_files/
Cache example:
cache:
key: "$CI_BUILD_REF_NAME"
untracked: true
paths:
- node_modules/
- src/bower_components/
For correct running environment i suggest using docker with image containing apt-get dependencies. And use artefacts for passing job results between jobs. Note that artefact also uploaded to gitlab web interface and being able to download them. So if they are quite heavy use small expire_in time, for removing them after all jobs done.
| GitLab | 31,623,924 | 15 |
I am running the AWS AMI from gitlab. I am trying to access the postgres database directly using psql. I thought I could just use the credentials in database.yml, since the rails application is working fine:
/opt/gitlab/embedded/bin/psql -U gitlab -d gitlabhq_production
But I get:
psql: FATAL: Peer authentication failed for user "gitlab"
How can the rails app be connecting to the database while psql cannot?
| sudo -u gitlab-psql /opt/gitlab/embedded/bin/psql -h /var/opt/gitlab/postgresql/ gitlabhq_production
| GitLab | 30,282,149 | 15 |
I am trying to pull a repo from github and push it up to a private repo on a gitlab server that I am running.
I cloned the github repo to my local machine
git clone https://github.com/somepage/someproject
at that point I added a new remote (my gitlab)
git remote add gitlab https://mygitlabserver/mypage/myproject
then I pushed (in this case only branch on githab was develop)
git push gitlab develop
Now I am running into problems when I try to clone from my gitlab repo:
git clone https://mygitlabserver/mypage/myproject
Cloning into 'myproject'...
remote: Counting objects: 140, done.
remote: Compressing objects: 100% (85/85), done.
remote: Total 140 (delta 40), reused 140 (delta 40)
Receiving objects: 100% (140/140), 2.75 MiB | 1.85 MiB/s, done.
Resolving deltas: 100% (40/40), done.
Checking connectivity... done.
warning: remote HEAD refers to nonexistent ref, unable to checkout.
Not 100% what that warning is about, but I am sure its not good. If I list the contents of that cloned dir its empty.
What did I do wrong?
| I suspect you are getting that error because the default configuration of a repository in gitlab is to have a default branch name of master. You have only pushed a branch named develop, and when you clone the repository git is attempting to checkout the nonexistent master branch.
You can:
go into the repository settings in gitlab and set the default branch to develop,
or you can just name the branch master,
or you can provide -b develop to the git clone command,
or after cloning you can simply git checkout develop.
| GitLab | 29,433,701 | 15 |
I started exploring Gitlab for version control management and I got an issue at the first step itsself. When ever I create a project its creating a new repository. I have few webapplications which are independent to each other. In that case do I need to use different repository for every project.
What I am looking for is what is what and when to use what but not able to find what is repository and what is project in gitlab website as well as through other sources as well.
Also I came across a term submodule, when can it be used. Can I create one global project and have all the webapplications as different submodules.
Can any one please help me in understanding the difference between those 3 and when to use what based on their intended way of usage. Also please help me by pointing to a good learning site where I can get the information of doing basic version control operations in gitlab.
Thanks.
| Gitlab manages projects: a project has many features in addition of the Git repo it includes:
issues: powerful, but lightweight issue tracking system.
merge requests: you can review and discuss code before it is merged in the branch of your code.
wiki: separate system for documentation, built right into GitLab
snippets: Snippets are little bits of code or text.
So fear each repo you create, you get additional features in its associated project.
And you can manage users associated to that project.
See GitLab documentation for more.
The Git repo and Git submodule are pure Git notions.
In your case, a submodule might not be needed, unless you want a convenient way to remember the exact versions of different webapp repo, recorded in one parent repo.
But if that is the case, then yes, you can create one global project and have all the webapplications as different submodules.
Each of those submodules would have their own GitLab project (and Git repo).
| GitLab | 27,282,439 | 15 |
I'm using gitlab. When I go into the interface, on each branch I can download the source code as a zip, tar or whatsoever.
I am making rpm spec files for which I would need the possibility to download the tar ball using command line. since I added my rsa key i can do git clone without problems:
git clone http://gitlab/group/project.git
Cloning into 'project'...
remote: Counting objects: 1885, done.
remote: Compressing objects: 100% (826/826), done.
remote: Total 1885 (delta 1194), reused 1496 (delta 954)
Receiving objects: 100% (1885/1885), 1.30 MiB | 0 bytes/s, done.
Resolving deltas: 100% (1194/1194), done.
Checking connectivity... done
However doing
wget http://gitlab/group/project/repository/archive.zip
gets me these errors:
Resolving gitlab (gitlab)... 10.1.253.75
Connecting to gitlab (gitlab)|10.1.253.75|:80... connected.
HTTP request sent, awaiting response... 401 Unauthorized
Authorization failed.
| Since GitLab 6.2 and issue 5253, it should be:
GET /projects/:id/repository/archive
But that seems for internal use only, since you cannot know the id of a project as a user (only its name).
Don't forget, as shown in ability.rb, that downloading an archive is linked to a permission. Make sure you have that "download_code" permission set for your project.
Here, it must be a permission issue, because, for instance:
wget http://demo.gitlab.com/gitlab/gitlab-recipes/repository/archive.zip
That works just fine, and get the content of that project without any issue.
However, as the OP Chris Maes comments and mentions in issue 6645, as as illustrated by app/models/ability.rb:
if project && project.public?
... that "dowload_code" feature is only for public projects.
| GitLab | 22,691,197 | 15 |
when opening a project in gitlab, you will see SSH and HTTP(or HTTPS) url on the top of project home page, the SSH url is as default, but I want to set HTTP(or HTTPS) as default, so how should I do? Thanks
| infact, you have to modify 2 other lines above the default_clone_protocol.
def default_url_to_repo(project = nil)
project = project || @project
current_user ? project.http_url_to_repo : project.url_to_repo
end
def default_clone_protocol
current_user ? "http" : "ssh"
end
| GitLab | 21,203,344 | 15 |
I understand that gitlab has support to Jenkins CI, but what I need is a lot less than that.
I have a Rails application and get the coverage from the tests using simplecov. It generates HTML output in a directory by running a rake task. I would like to see the current coverage through gitlab. Is there a simple way to integrate this report with gitlab?
| I fear there is still no easy way to integrate code coverage reports but Gitlab now supports (since Version 8.0 integrated) build jobs for your code. Unfortunately you have to implement your solution by writing a custom .gitlab-ci.yml to run your coverage tests. For viewing the reports, you can specify the generated "artifacts" or publish them on gitlab pages.
For more information, see here: https://about.gitlab.com/gitlab-ci/
Additionally you can parse a text output to display a short code coverage report:
(Enable builds and output test coverage)
Go to "Project Settings" -> Builds
Add to "Test coverage parsing" a regular expression (examples below, simplecov included)
| GitLab | 17,811,917 | 15 |
I recognize that this is a duplicate question however all the other answers I've found related to this issue have not seemed to help me...
I'm installing GitLab and running through the gem dependencies when it hits the NokoGiri gem requirement and fails with the following info:
ERROR: Error installing nokogiri:
ERROR: Failed to build gem native extension.
/usr/local/bin/ruby extconf.rb
extconf.rb:10:in `<main>': Use RbConfig instead of obsolete and deprecated Config.
extconf.rb:10:in `<main>': Use RbConfig instead of obsolete and deprecated Config.
extconf.rb:11:in `<main>': Use RbConfig instead of obsolete and deprecated Config.
checking for libxml/parser.h... yes
checking for libxslt/xslt.h... yes
checking for libexslt/exslt.h... yes
checking for iconv_open() in iconv.h... yes
checking for xmlParseDoc()... -lxml2
checking for xsltParseStylesheetDoc()... -lxslt
-----
libxslt is missing. please visit http://nokogiri.org/tutorials/installing_nokogiri.html for help with installing dependencies.
-----
So, this error leads me down the path of attempting to install libxslt with the following command:
$ sudo apt-get install libxslt-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'libxslt1-dev' instead of 'libxslt-dev'
libxslt1-dev is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 146 not upgraded.
So what gives? NokoGiri is needing this package, but the package is already installed!! I can't seem to get past this issue, any help out there?
| first make sure you have all the dependencies, as mentioned in "Installing Nokogiri with RVM on Ubuntu" (which mentions the very same error message)
I have no idea why it can't find the package "libxslt". Instead of worrying about that, I'm going to install the dependencies listed on Nokogiri GitHub page:
$ sudo apt-get install libxslt-dev libxml2-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'libxslt1-dev' instead of 'libxslt-dev'
libxslt1-dev is already the newest version.
libxml2-dev is already the newest version.
That appears to have worked well enough, so I press on. The next step is install the actual Nokogiri gem. The instructions say to use "sudo gem install nokogiri", but because I'm using RVM, I drop the "sudo" part:
$ gem install nokogiri
Considering "Fresh install of RVM in Ubuntu isn't letting me install gems (zlib error)", since you have libxslt1-dev (and not libxslt-dev), you might considering recompiling your ruby.
(a bit like in "How to get Readline support in IRB using RVM on Ubuntu 11.10")
| GitLab | 16,084,144 | 15 |
I'm dealing with a GitLab Community Edition 13.10.1.
At the moment there are about a hundred small projects on this.
By selecting a project it is possible to search for specific code within all its files, but if instead I go to the GitLab search and select "Any" project, the "Code" tab is no longer visible.
Is there a way to do a code search, but within all the existing existing projects?
| You can use GitLab Advanced Search to search for code if you are subscribed to the premium tier.
Another option would be to use the opensource gitlab-search tool if you are using the community edition.
| GitLab | 69,466,442 | 14 |
Some time ago, our Gitlab (self-hosted) instance started to throw errors that the archives are too big:
ERROR: Uploading artifacts as "archive" to coordinator... too large
archive id=something responseStatus=413 Request Entity Too Large
status=413 token=something FATAL: too large
ERROR: Job failed: exit code 1
The only resolution ideas we found was to set the max build artifact size (it's under /admin/application_settings). This did not work for us, the error still occurred.
Reference articles:
https://gitlab.com/gitlab-com/gl-infra/infrastructure/-/issues/3813
https://dzone.com/articles/gitlab-ci-runner-artifacts-size-error-quottoo-larg
https://www.kevinhooke.com/2018/07/30/gitlab-ci-runner-artifacts-size-error-too-large-archive/
https://forum.gitlab.com/t/uploading-artifacts-too-large-archive-error-413/4867
How to increase maximum artifacts size for Gitlab on-premises
| From gitlab official docs:
The maximum size of the job artifacts can be set at:
The value is in MB and the default is 100MB per job.
To change it at the instance level:
On the top bar, select Menu > Admin.
On the left sidebar, select Settings > CI/CD.
Change the value of maximum artifacts size (in MB).
Select Save changes for the changes to take effect.
Group level (this overrides the instance setting):
To change it at the group level:
Go to the group’s Settings > CI/CD > General Pipelines.
Change the value of maximum artifacts size (in MB).
Select Save changes for the changes to take effect.
Project level (this overrides the instance and group settings):
To change it at the project level:
Go to the project’s Settings > CI/CD > General Pipelines.
Change the value of maximum artifacts size (in MB).
Select Save changes for the changes to take effect.
Ref: Maximum artifacts size
| GitLab | 64,329,087 | 14 |
I have a remote runner:
ci$ gitlab-runner --version Version: 12.2.0
The .gitlab-ci.yml :
stages:
- build
- deploy
variables:
LANG: "en_US.UTF-8"
LC_ALL: "en_US.UTF-8"
build:
tags:
- ios
stage: build
script:
- bundle exec fastlane build
except:
- develop
- master
- /^rc\/.*$/
environment:
name: production
deploy:
tags:
- ios
stage: deploy
before_script:
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client git -y )'
- eval $(ssh-agent -s)
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- ssh-keyscan gitlab.com >> ~/.ssh/known_hosts
- chmod 644 ~/.ssh/known_hosts
- ssh -vv [email protected]
- git config --global user.email "[email protected]"
- git config --global user.name "username"
- git branch
- git branch -r
script:
- bundle exec fastlane deploy
only:
- develop
- master
- /^rc\/.*$/
environment:
name: production
post:
stage: .post
when: always
script:
- bundle exec fastlane clear_data_CI
Gitlab CI fails to run, drops this warning first:
This job is stuck because the project doesn't have any runners online
assigned to it.
Go to Runners page
And later:
There has been a timeout failure or the job got stuck. Check your
timeout limits or try again
So tags are added, but it stopped running. Remote runner is working properly. Any issues?
| You have to make sure that the remote runner you are referring to is:
Actually running
Listed as an activated runner in your project's Runners section
Configured to follow/listen to the same tags
Go to your repo's Gitlab project settings. Then find the section for CI / CD > Runners. You should see something like the image below:
Here we see that there is a runner (df51f559) configured for the project, and it is running (green). If your repo's .gitlab-ci.yml is using tags, then that runner must also have the same tags. So here, if your job is expecting a runner with ios tag, then this UI should also show the runner to have an ios tag.
You can verify the runner token using gitlab-runner verify or list:
root@buildpc:~# gitlab-runner verify
...
Verifying runner... is alive runner=df51f559
root@buildpc:~# gitlab-runner list
my-runner Executor=docker Token=df51f55995e68cccb3ada8c1458ec7 URL=http://192.168.1.61/
Here my-runner's
Token must match the token displayed in the Runners page
URL must match the base URL of your Gitlab project
If you can't see an activated runner, that section has instructions on how to register a new runner for your project. You can also refer to Gitlab's Registering Runners help docs.
If you have admin access to your Gitlab instance, you can also go to the Admin dashboard, Runners, select a runner from the available ones, then manually add it to your project. You can also edit the tags.
Lastly, as mentioned in the comments, if you originally had no active runners then you successfully added one, you need to restart the job. AFAIK, when a job gets stuck because there is no runner, it does not automatically resume when a runner becomes available. You'll have to manually retry or re-trigger the job.
| GitLab | 60,109,622 | 14 |
I have created a pipeline in gitlab, with
image:
name: hashicorp/terraform:light
entrypoint:
- '/usr/bin/env'
- 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
variables:
PLAN: dbrest.tfplan
STATE: dbrest.tfstate
cache:
paths:
- .terraform
before_script:
- terraform --version
- terraform init
stages:
- validate
- build
- deploy
- destroy
validate:
stage: validate
script:
- terraform validate
plan:
stage: build
script:
- terraform plan -state=$STATE -out=$PLAN
artifacts:
name: plan
paths:
- $PLAN
- $STATE
apply:
stage: deploy
environment:
name: production
script:
- terraform apply -state=$STATE -input=false $PLAN
- terraform state show aws_instance.bastion
dependencies:
- plan
when: manual
only:
- master
destroy:
stage: destroy
environment:
name: production
script:
- terraform destroy -state=$STATE -auto-approve
dependencies:
- apply
when: manual
only:
- master
I have also created a variable under 'Settings. -> 'CI/CD' -> 'Variables' - I was under the impression that when I came to the manual stage deploy, gitlab should pause and ask me to input a value for that variable, but this does not happen - what is missing?
| You have mixed a job with when: manual to when you trigger a pipeline manually. This is the one you want:
https://docs.gitlab.com/ee/ci/pipelines/#run-a-pipeline-manually
You could use this together with an only for some variable. Something like:
...
apply:
stage: deploy
environment:
name: production
script:
- terraform apply -state=$STATE -input=false $PLAN
- terraform state show aws_instance.bastion
dependencies:
- plan
only:
refs:
- master
variables:
- $RELEASE == "yes"
destroy:
stage: destroy
environment:
name: production
script:
- terraform destroy -state=$STATE -auto-approve
dependencies:
- apply
only:
refs:
- master
variables:
- $RELEASE == "yes"
With something like this, you can have jobs that are never run normally, but only if you manually start a new pipeline on the master branch and set the variable $RELEASE to yes. I haven't tested this, so my apologies if it doesn't work!
| GitLab | 58,710,222 | 14 |
The error below is triggered when executing kubectl -n gitlab-managed-apps logs install-helm.
I've tried regenerating the certificates, and bypassing the certificate check. Somehow it is using my internal certificate instead of the certificate of the source.
root@dev # kubectl -n gitlab-managed-apps logs install-helm
+ helm init --tiller-tls --tiller-tls-verify --tls-ca-cert /data/helm/helm/config/ca.pem --tiller-tls-cert /data/helm/helm/config/cert.pem --tiller-tls-key /data/helm/helm/config/key.pem
Creating /root/.helm
Creating /root/.helm/repository
Creating /root/.helm/repository/cache
Creating /root/.helm/repository/local
Creating /root/.helm/plugins
Creating /root/.helm/starters
Creating /root/.helm/cache/archive
Creating /root/.helm/repository/repositories.yaml
Adding stable repo with URL: https://kubernetes-charts.storage.googleapis.com
Error: Looks like "https://kubernetes-charts.storage.googleapis.com" is not a valid chart repository or cannot be reached: Get https://kubernetes-charts.storage.googleapis.com/index.yaml: x509: certificate is valid for *.tdebv.nl, not kubernetes-charts.storage.googleapis.com
What might be the issue here? Screenshot below is the error Gitlab is giving me (not much information either).
| After having the same issue I finally found the solution for it:
In the /etc/resolv.conf file on your Master and Worker nodes you have to search and remove the search XYZ.com entry.
If you are using Jelastic you have to remove this entry every time after a restart. It gets added by Jelastic automatically. I already contacted them so maybe they will fix it soon.
| GitLab | 54,163,478 | 14 |
I am using Gitlab for repository and ci/cd.
Currently trying to set up pipeline that creates a docker image from a build stage.
All examples I have seen have a simple naming of image where e.g. the branch is used(master)
My question is if I want to tag the image based on the current tag in the repository how do I do this?
I am presuming I can use a Gitlab runner variable but do not see one to us
| There are a lot of predefined variables in Gitlab CI. I think you are looking for CI_COMMIT_TAG.
So you could use it this way:
docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG
So the image would look like registry.example.com/group/project:tag
| GitLab | 51,431,684 | 14 |
Is it possible to have one git repo placed on both github and gitlab?
So that if you push to a remote repo that its both on Github and Gitlab.
| You have misunderstood how Git works. Or how content hosting works.
First of all, your repo is not on GitHub nor GitLab. Your repo is on your hard disk, right there where you cloned or created it. This is a repository. Local one. This is where you do the work *)
On GitHub and on GitLab you can setup remote copy of your repository. Then, after you did some work on your local repo, you can instruct your local repo to send those new bits of work to that remote copy. Or to another remote copy. Or to 50 remote copies held in different places.
Second fact is, GitHub and GitLab are separate. In fact, there is one GitHub, but there is no single GitLab. There are many GitLabs out there, you can even buy a server and host your own GitLab. This only emphasises that they are all separate. Whatever you send to GitHub will NOT magically show up on GitLab1, nor GitLab2, nor (..)
Third fact, they are all separate, but they all allow you to host copies of your git repo. Since you can instruct your local repo to send things to multiple remotes, you can have them all in sync.
However, pasting all the URLs to all servers each time you want to do a push would be cumbersome, so your local git repo can be taught to know the remote locations and remember them for you. This called remotes and you probably saw it already in form:
git push origin master
\ \
\ branch to be pushed
name of the remote
origin is the typical name for the-single-remote-server you work with. But if you want to have many, you probably want to set some meaningful names, like:
git remote add remote-github (url-to-repo-on-github)
git remote add remote-gitlab1 (url-to-repo-on-gitlab1)
git remote add remote-gitlab2 (url-to-repo-on-gitlab2)
...
This sets up 3+ remotes with different names. Now you can:
git push remote-github master
git push remote-gitlab1 master
and so on. That will work - basically, do code changes, commit, push them to 3+ servers, and you have "same things on GitHub and GitLab". Keep in mind that if you are not alone and if you let someone work on your code on GitHub/GitLab separately, everyone would need to push to all remotes at the same time and in the same order, or else it can diverge quickly.
Manually pushing to 2+ remotes can be somewhat cumbersome too, even if they are remembered by their names. That's why recent Git versions allow to set multiple push URLs under single name of a remote.
Also, Git repositories, and some Git hostings, support "triggers" or "hooks". These things allow you to set a script that will be executed every time something happens. Something like a commit or push. Using that you could instruct your hosting to, for example, at every received push do a push to the other remote repo. But I won't cover it, here&now, I think you already have enough keywords to search for!
*) well, except for some semi-automated things like PRs/MRs/Reviews/Issues/etc - but that's specific to your workflow and support for it on the hosting site. Obviously, since sites are separate, and since support for features may differ, PRs/MRs/Reviews/../etc performed on one site will not magically transfer to other sites. If the specific feature is implemented via branches, then you can sync that via some hooks&scripting. Otherwise, you'd need to find a proper plugin for the site. Or, well, write it yourself. IIRC, at least GitLab has an API for that.
| GitLab | 50,686,889 | 14 |
I have my .gitlab-ci.yml file set up in the typical three stages: test, build, deploy. During the build stage, I run a command that compiles my project and puts it in a tarball. The build stage appears to execute successfully because it moves on to the deploy stage, but the deploy stage then says it can't find the tarball. Is it in another directory? What happened to it? Thanks.
| For each test gitlab-ci clean the build folder, therefore the output files of the build stage are not available in the deploy stage.
You need to rebuild your project also in the deploy stage.
The "stages" are only useful to order your tests, i.e. avoid to try to do a deploy test if a build test failed.
EDIT:
Since Gitlab 8.6, it is possible using dependencies feature
| GitLab | 33,409,863 | 14 |
We are using Gitlab (7.10.2) and Redmine (3.0.2).
All issues are managed in Redmine and Gitlab manages all git-repositories.
We set up Gitlab via the UI so far that commits with the message 'Close #234' are clickable and pointing to the corresponding Redmine ticket website.
We now want to achieve that tickets in Redmine are directly linked with Gitlab commits.
If we are using the internal Gitlab issue system and set the commit-message to ‘Close #234’ the ticket 234 is automatic closed and linked with the commit.
But with Redmine as issue service system we are not able to automatic close issues with commits or have any information about this in Redmine.
Does anyone knows how we can modify Gitlab and/or Redmine to close Redmine tickets with Gitlab commits?
| You can use Redmine as an issue tracker with setting the redmine service in Gitlab (In your project -> Services -> Redmine -> fill the URLs, and set active). If this works, when you press "new issue" button in Gitlab, you are redirected to Redmine new issue page. In Gitlab you should have WebHook to inform the Redmine about new push into the repo. This can be set in the settings "In your project -> Settings -> Web hooks" (how, see here).
In Redmine go to Administration -> Settings -> Repositories. Check your referencing keywords. "closes" or "close" should be in the list. Finally in the same tab there is the table at the bottom, where you choose tracker, your fixing keyword (closes, close), set applied status to "Closed", and choose the appropriate amount of % Done (100%).
Similarly you can set other keywords to change status in Redmine tickets.
Use the redmine_gitlab_hook to keep Redmine repo up-to date.
| GitLab | 30,177,291 | 14 |
Scenario: we are 3 developers.
Developer 1 (admin) created the main repo.
Developer 2 forked admin's repo.
Developer 3 forked admin's repo.
Developer 2 created a feature branch "Feature 1"
Developer 3 checked out "Feature 1" from developer 2 repo.
When Developer 3 tries to create a Merge Request he only sees his own and admin's repos.
So I wonder, Is it possible to create a Merge Request to another remote different than my fork's?"
The only work-around I have seen so far is:
Developer 2 pushes the feature branch to admin's repo (through a merge request) and asks the admin to "protect it", then Developer 3 would have to create a merge request to admin's repo as well, the problem with this approach is that Developer 2 loses the ownership of the branch and they will have to create merge requests every time they want to push their changes.
On the other hand, it seems like this feature was added to GitLab but I can't find the official documentation about this feature.
| No forks, maybe?
You may utilise the fact, that merge requests can be made within the same repository. So maybe all three may use the same repository as developers, the admin should set the crucial branches as protected.
If any change is made, anyone can create a merge request from one branch to another... and anyone can review, discuss, ...
| GitLab | 28,950,433 | 14 |
I don't think I'm really understanding how Gerrit can fit into my group's existing workflow. Is Gerrit intended to be the central "hub" of code? I have been imagining it as similar to Atlassian's Crucible, which fits in with Atlassian's Stash or Bitbucker.
My group currently uses a very active Gitlab installation but the built-in code review facility is lacking, and I absolutely must inspect code from contractors going into the repo.
I need a behind-the-firewall solution, and cost is a big consideration. I have heard positive things about Gerrit, but not really an explanation of how it can fit into an existing process. I also like that it seems to have pretty good eclipse integration.
Can someone help me out?
| Gerrit expects to "own" the repositories you use it with, i.e. it expects the git directories to be present in a mounted file system. If you want it to interact with GitLab (or GitHub) you can set up one way replication from Gerrit to GitLab so that changes made in Gerrit will be pushed to GitLab within a few seconds. For GitHub there's a Gerrit GitHub plugin to help with this.
You can continue to use the other features of GitLab but if you don't lock down the repositories (or at least block pushes into branches that Gerrit manages) you'll end up in trouble the next time Gerrit attempts to replicate to the GitLab repository.
So... Gerrit does replace GitLab's repository management and code review facilities but doesn't contain an issue tracker, wiki, or similar.
| GitLab | 25,880,670 | 14 |
This is what I tried:
curl http://git.ep.petrobras.com.br/api/v3/session --data-urlencode 'login=myUser&password=myPass'
Answer:
{"message":"401 Unauthorized"}
| The problem is the data-urlencode CURL option. Since it's an HTTP POST you don't need to URL encode the data, and is actually encoding the & into & and causing your issue. Instead use the --data option.
curl http://git.ep.petrobras.com.br/api/v3/session --data 'login=myUser&password=myPass'
Also, be careful sending credentials over plain HTTP. It could be easily sniffed.
| GitLab | 23,640,961 | 14 |
I just recently install GitLab v5.0 on an Ubuntu 12.04 server and am now having issues with email notifications. I can't get GitLab to send any emails of any kind.
I've got my config/environments/production.rb file setup to use sendmail as the transport service:
config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
And I can manually use sendmail successfully from the shell as described here: http://scratching.psybermonkey.net/2011/03/sendmail-how-to-test-sending-email.html
My config/gitlab.yml file is setup with the following email setting:
email_from: [email protected]
I've read that it could be a problem with Sidekiq not running so I ran the following command but nothing has changed.. I still can't send emails:
$ sudo -u git -H bundle exec rake sidekiq:start RAILS_ENV=production
$ ps aux |grep -i sidekiq
git 2791 2.1 4.2 206476 86620 pts/0 Sl 14:45 0:23 sidekiq 2.7.5 gitlab [0 of 25 busy]
Which indicates to me that Sidekiq is indeed running... what else could be the issue here? There doesn't seem to be much documentation on GitLab's wiki regarding email settings unfortunately...
I found the following error being logged in sidekiq.log:
2013-04-24T21:09:01Z 2791 TID-1jaur8 Sidekiq::Extensions::DelayedMailer JID-21bd3ec0f086351088992396 INFO: start
2013-04-24T21:09:01Z 2791 TID-1jaur8 Sidekiq::Extensions::DelayedMailer JID-21bd3ec0f086351088992396 INFO: fail: 0.004 sec
2013-04-24T21:09:01Z 2791 TID-1jaur8 WARN: {"retry"=>true, "queue"=>"default", "timeout"=>30, "class"=>"Sidekiq::Extensions::DelayedMailer", "args"=>["---\n- !ruby/class 'Notify'\n- :new_user_email\n- - 4\n - pSzzULp8\n"], "at"=>1366819034.5969028, "jid"=>"21bd3ec0f086351088992396", "error_message"=>"Couldn't find User with id=4", "error_class"=>"ActiveRecord::RecordNotFound", "failed_at"=>"2013-04-24T15:57:19Z", "retry_count"=>10, "retried_at"=>2013-04-24 21:09:01 UTC}
2013-04-24T21:09:01Z 2791 TID-1jaur8 WARN: Couldn't find User with id=4
2013-04-24T21:09:01Z 2791 TID-1jaur8 WARN: /home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/relation/finder_methods.rb:343:in `find_one'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/relation/finder_methods.rb:314:in `find_with_ids'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/relation/finder_methods.rb:107:in `find'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/querying.rb:5:in `find'
/home/git/gitlab/app/mailers/notify.rb:23:in `new_user_email'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/base.rb:167:in `process_action'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/base.rb:121:in `process'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/rendering.rb:45:in `process'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/actionmailer-3.2.13/lib/action_mailer/base.rb:459:in `process'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/actionmailer-3.2.13/lib/action_mailer/base.rb:453:in `initialize'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/actionmailer-3.2.13/lib/action_mailer/base.rb:439:in `new'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/actionmailer-3.2.13/lib/action_mailer/base.rb:439:in `method_missing'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/extensions/action_mailer.rb:20:in `perform'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/processor.rb:45:in `block (3 levels) in process'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/chain.rb:109:in `call'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/chain.rb:109:in `block in invoke'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/server/timeout.rb:11:in `block in call'
/usr/local/lib/ruby/1.9.1/timeout.rb:68:in `timeout'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/server/timeout.rb:10:in `call'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/chain.rb:111:in `block in invoke'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/server/active_record.rb:6:in `call'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/chain.rb:111:in `block in invoke'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/server/retry_jobs.rb:49:in `call'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/chain.rb:111:in `block in invoke'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/server/logging.rb:11:in `block in call'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/logging.rb:22:in `with_context'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/server/logging.rb:7:in `call'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/chain.rb:111:in `block in invoke'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/chain.rb:114:in `call'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/middleware/chain.rb:114:in `invoke'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/processor.rb:44:in `block (2 levels) in process'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/processor.rb:80:in `stats'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/sidekiq-2.7.5/lib/sidekiq/processor.rb:43:in `block in process'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/celluloid-0.12.4/lib/celluloid/calls.rb:23:in `call'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/celluloid-0.12.4/lib/celluloid/calls.rb:23:in `public_send'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/celluloid-0.12.4/lib/celluloid/calls.rb:23:in `dispatch'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/celluloid-0.12.4/lib/celluloid/future.rb:18:in `block in initialize'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/celluloid-0.12.4/lib/celluloid/internal_pool.rb:48:in `call'
/home/git/gitlab/vendor/bundle/ruby/1.9.1/gems/celluloid-0.12.4/lib/celluloid/internal_pool.rb:48:in `block in create'
Any ideas?
| This is my entries at the end in /config/environment/production.rb and that is working for me.
Comment out sendmail options and use external SMTP relays
##config.action_mailer.delivery_method = :sendmail ## Comment out this
# Defaults to:
## config.action_mailer.sendmail_settings = {
## :location => '/usr/sbin/sendmail',
## :arguments => '-i -t'
## }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
## SMTP Settings
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => '10.146.10.90', ## My SMTP Relay/Gateway
:port => 25, ## SMTP Port
:domain => 'gitlab.example.com', ## My Domain
:authentication => :plain, ## Let it be plain as it is inside my LAN
##:user_name => '[email protected]', ## This is not required as long as
##:password => 'yourPassword', ## SMTP Gateway allows anonymous relay
##:enable_starttls_auto => true ## In LAN
##:user_name => '',
##:password => '',
:enable_starttls_auto => true
}
end
| GitLab | 16,201,090 | 14 |
I have a file (say called list.txt) that contains relative paths to files, one path per line, i.e. something like this:
foo/bar/file1
foo/bar/baz/file2
goo/file3
I need to write a bash script that processes one path at a time, splits it at the last slash and then launches another process feeding it the two pieces of the path as arguments. So far I have only the looping part:
for p in `cat list.txt`
do
# split $p like "foo/bar/file1" into "foo/bar/" as part1 and "file1" as part2
inner_process.sh $part1 $part2
done
How do I split? Will this work in the degenerate case where the path has no slashes?
| Use basename and dirname, that's all you need.
part1=$(dirname "$p")
part2=$(basename "$p")
| Split | 13,767,252 | 108 |
I have a data frame with 10 columns, collecting actions of "users", where one of the columns contains an ID (not unique, identifying user)(column 10). the length of the data frame is about 750000 rows. I am trying to extract individual data frames (so getting a list or vector of data frames) split by the column containing the "user" identifier, to isolate the actions of a single actor.
ID | Data1 | Data2 | ... | UserID
1 | aaa | bbb | ... | u_001
2 | aab | bb2 | ... | u_001
3 | aac | bb3 | ... | u_001
4 | aad | bb4 | ... | u_002
resulting into
list(
ID | Data1 | Data2 | ... | UserID
1 | aaa | bbb | ... | u_001
2 | aab | bb2 | ... | u_001
3 | aac | bb3 | ... | u_001
,
4 | aad | bb4 | ... | u_002
...)
The following works very well for me on a small sample (1000 rows):
paths = by(smallsampleMat, smallsampleMat[,"userID"], function(x) x)
and then accessing the element I want by paths[1] for instance.
When applying on the original large data frame or even a matrix representation, this chokes my machine ( 4GB RAM, MacOSX 10.6, R 2.15) and never completes (I know that a newer R version exists, but I believe this is not the main problem).
It seems that split is more performant and after a long time completes, but I do not know ( inferior R knowledge) how to piece the resulting list of vectors into a vector of matrices.
path = split(smallsampleMat, smallsampleMat[,10])
I have considered also using big.matrix etc, but without much success that would speed up the process.
| You can just as easily access each element in the list using e.g. path[[1]]. You can't put a set of matrices into an atomic vector and access each element. A matrix is an atomic vector with dimension attributes. I would use the list structure returned by split, it's what it was designed for. Each list element can hold data of different types and sizes so it's very versatile and you can use *apply functions to further operate on each element in the list. Example below.
# For reproducibile data
set.seed(1)
# Make some data
userid <- rep(1:2,times=4)
data1 <- replicate(8 , paste( sample(letters , 3 ) , collapse = "" ) )
data2 <- sample(10,8)
df <- data.frame( userid , data1 , data2 )
# Split on userid
out <- split( df , f = df$userid )
#$`1`
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
#$`2`
# userid data1 data2
#2 2 xfv 4
#4 2 bfe 10
#6 2 mrx 2
#8 2 fqd 9
Access each element using the [[ operator like this:
out[[1]]
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
Or use an *apply function to do further operations on each list element. For instance, to take the mean of the data2 column you could use sapply like this:
sapply( out , function(x) mean( x$data2 ) )
# 1 2
#3.75 6.25
| Split | 18,527,051 | 107 |
I need help with the split() method.
I have the followingString:
String values = "0|0|0|1|||0|1|0|||";
I need to put the values into an array. There are 3 possible strings: "0", "1", and ""
My problem is, when i try to use split():
String[] array = values.split("\\|");
My values are saved only until the last 0. Seems like the part "|||" gets trimmed.
What am i doing wrong?
thanks
| This behavior is explicitly documented in String.split(String regex) (emphasis mine):
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
If you want those trailing empty strings included, you need to use String.split(String regex, int limit) with a negative value for the second parameter (limit):
String[] array = values.split("\\|", -1);
| Split | 14,414,582 | 107 |
I need to split a JavaScript array into n sized chunks.
E.g.: Given this array
["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]
and a n equals to 4, the output should be this:
[ ["a1", "a2", "a3", "a4"],
["a5", "a6", "a7", "a8"],
["a9", "a10", "a11", "a12"],
["a13"]
]
I aware of pure JavaScript solutions for this problem, but since I am already using Lodash I am wondering if Lodash provides a better solution for this.
Edit:
I created a jsPerf test to check how much slower the underscore solution is.
| Take a look at lodash' chunk: https://lodash.com/docs#chunk
const data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"];
const chunks = _.chunk(data, 3);
console.log(chunks);
// [
// ["a1", "a2", "a3"],
// ["a4", "a5", "a6"],
// ["a7", "a8", "a9"],
// ["a10", "a11", "a12"],
// ["a13"]
// ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
| Split | 8,566,667 | 106 |
On a Linux desktop (RHEL4) I want to extract a range of bytes (typically less than 1000) from within a large file (>1 Gig). I know the offset into the file and the size of the chunk.
I can write code to do this but is there a command line solution?
Ideally, something like:
magicprogram --offset 102567 --size 253 < input.binary > output.binary
| Try dd:
dd skip=102567 count=253 if=input.binary of=output.binary bs=1
The option bs=1 sets the block size, making dd read and write one byte at a time. The default block size is 512 bytes.
The value of bs also affects the behavior of skip and count since the numbers in skip and count are the numbers of blocks that dd will skip and read/write, respectively.
| Split | 1,423,346 | 105 |
I am new in Java although had a good experience in PHP, and looking for perfect replacement for explode and implode (available in PHP) functions in Java.
I have Googled for the same but not satisfied with the results.
Anyone has the good solution for my problem will be appreciated.
For example:
String s = "x,y,z";
//Here I need a function to divide the string into an array based on a character.
array a = javaExplode(',', s); //What is javaExplode?
System.out.println(Arrays.toString(a));
Desired output:
[x, y, z]
| The Javadoc for String reveals that String.split() is what you're looking for in regard to explode.
Java does not include a "implode" of "join" equivalent. Rather than including a giant external dependency for a simple function as the other answers suggest, you may just want to write a couple lines of code. There's a number of ways to accomplish that; using a StringBuilder is one:
String foo = "This,that,other";
String[] split = foo.split(",");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
sb.append(split[i]);
if (i != split.length - 1) {
sb.append(" ");
}
}
String joined = sb.toString();
| Split | 16,773,599 | 104 |
I have a small function I found that takes a string from a textarea and then puts it into a canvas element and wraps the text when the line gets too long. But it doesn't detect line breaks. This is what it's doing and what it should do:
Input:
Hello
This is dummy text that could be inside the text area.
It will then get put into the canvas.
Wrong output:
Hello this is dummy text
that could be inside the
text area. It will then
get put into the canvas.
What it should output:
Hello
This is dummy text that
could be inside the text
area. It will then get
put into the canvas.
This is the function I'm using:
function wrapText(context, text, x, y, maxWidth, lineHeight) {
var words = text.split(' ');
var line = '';
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}
context.fillText(line, x, y);
}
Is it possible to achieve what I'm trying to get? Or is there a way to simply move the text area as is into the canvas?
| Using .split():
var str = `your text
that spans
multiple lines`
// Split the string on \n or \r characters
var separateLines = str.split(/\r?\n|\r|\n/g);
alert("Total number of separate lines is: " + separateLines.length);
Or using .match() instead:
var str = `your text
that spans
multiple lines`
// Split the string on \n or \r characters
var separateLines = str.match(/[^\r\n]+/g);
alert("Total number of separate lines is: " + separateLines.length);
| Split | 21,711,768 | 103 |
I have string for example: "238 NEO Sports". I want to split this string only at the first space. The output should be ["238","NEO Sports"].
One way I could think of is by using split() and finally merging the last two strings returned. Is there a better way?
| Just pass the count as second parameter to str.split function.
>>> s = "238 NEO Sports"
>>> s.split(" ", 1)
['238', 'NEO Sports']
| Split | 30,636,248 | 101 |
I'm trying to convert some code from Python to C++ in an effort to gain a little bit of speed and sharpen my rusty C++ skills. Yesterday I was shocked when a naive implementation of reading lines from stdin was much faster in Python than C++ (see this). Today, I finally figured out how to split a string in C++ with merging delimiters (similar semantics to python's split()), and am now experiencing deja vu! My C++ code takes much longer to do the work (though not an order of magnitude more, as was the case for yesterday's lesson).
Python Code:
#!/usr/bin/env python
from __future__ import print_function
import time
import sys
count = 0
start_time = time.time()
dummy = None
for line in sys.stdin:
dummy = line.split()
count += 1
delta_sec = int(time.time() - start_time)
print("Python: Saw {0} lines in {1} seconds. ".format(count, delta_sec), end='')
if delta_sec > 0:
lps = int(count/delta_sec)
print(" Crunch Speed: {0}".format(lps))
else:
print('')
C++ Code:
#include <iostream>
#include <string>
#include <sstream>
#include <time.h>
#include <vector>
using namespace std;
void split1(vector<string> &tokens, const string &str,
const string &delimiters = " ") {
// Skip delimiters at beginning
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first non-delimiter
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos) {
// Found a token, add it to the vector
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters
lastPos = str.find_first_not_of(delimiters, pos);
// Find next non-delimiter
pos = str.find_first_of(delimiters, lastPos);
}
}
void split2(vector<string> &tokens, const string &str, char delim=' ') {
stringstream ss(str); //convert string to stream
string item;
while(getline(ss, item, delim)) {
tokens.push_back(item); //add token to vector
}
}
int main() {
string input_line;
vector<string> spline;
long count = 0;
int sec, lps;
time_t start = time(NULL);
cin.sync_with_stdio(false); //disable synchronous IO
while(cin) {
getline(cin, input_line);
spline.clear(); //empty the vector for the next line to parse
//I'm trying one of the two implementations, per compilation, obviously:
// split1(spline, input_line);
split2(spline, input_line);
count++;
};
count--; //subtract for final over-read
sec = (int) time(NULL) - start;
cerr << "C++ : Saw " << count << " lines in " << sec << " seconds." ;
if (sec > 0) {
lps = count / sec;
cerr << " Crunch speed: " << lps << endl;
} else
cerr << endl;
return 0;
//compiled with: g++ -Wall -O3 -o split1 split_1.cpp
Note that I tried two different split implementations. One (split1) uses string methods to search for tokens and is able to merge multiple tokens as well as handle numerous tokens (it comes from here). The second (split2) uses getline to read the string as a stream, doesn't merge delimiters, and only supports a single delimeter character (that one was posted by several StackOverflow users in answers to string splitting questions).
I ran this multiple times in various orders. My test machine is a Macbook Pro (2011, 8GB, Quad Core), not that it matters much. I'm testing with a 20M line text file with three space-separated columns that each look similar to this: "foo.bar 127.0.0.1 home.foo.bar"
Results:
$ /usr/bin/time cat test_lines_double | ./split.py
15.61 real 0.01 user 0.38 sys
Python: Saw 20000000 lines in 15 seconds. Crunch Speed: 1333333
$ /usr/bin/time cat test_lines_double | ./split1
23.50 real 0.01 user 0.46 sys
C++ : Saw 20000000 lines in 23 seconds. Crunch speed: 869565
$ /usr/bin/time cat test_lines_double | ./split2
44.69 real 0.02 user 0.62 sys
C++ : Saw 20000000 lines in 45 seconds. Crunch speed: 444444
What am I doing wrong? Is there a better way to do string splitting in C++ that does not rely on external libraries (i.e. no boost), supports merging sequences of delimiters (like python's split), is thread safe (so no strtok), and whose performance is at least on par with python?
Edit 1 / Partial Solution?:
I tried making it a more fair comparison by having python reset the dummy list and append to it each time, as C++ does. This still isn't exactly what the C++ code is doing, but it's a bit closer. Basically, the loop is now:
for line in sys.stdin:
dummy = []
dummy += line.split()
count += 1
The performance of python is now about the same as the split1 C++ implementation.
/usr/bin/time cat test_lines_double | ./split5.py
22.61 real 0.01 user 0.40 sys
Python: Saw 20000000 lines in 22 seconds. Crunch Speed: 909090
I still am surprised that, even if Python is so optimized for string processing (as Matt Joiner suggested), that these C++ implementations would not be faster. If anyone has ideas about how to do this in a more optimal way using C++, please share your code. (I think my next step will be trying to implement this in pure C, although I'm not going to trade off programmer productivity to re-implement my overall project in C, so this will just be an experiment for string splitting speed.)
Thanks to all for your help.
Final Edit/Solution:
Please see Alf's accepted answer. Since python deals with strings strictly by reference and STL strings are often copied, performance is better with vanilla python implementations. For comparison, I compiled and ran my data through Alf's code, and here is the performance on the same machine as all the other runs, essentially identical to the naive python implementation (though faster than the python implementation that resets/appends the list, as shown in the above edit):
$ /usr/bin/time cat test_lines_double | ./split6
15.09 real 0.01 user 0.45 sys
C++ : Saw 20000000 lines in 15 seconds. Crunch speed: 1333333
My only small remaining gripe is regarding the amount of code necessary to get C++ to perform in this case.
One of the lessons here from this issue and yesterday's stdin line reading issue (linked above) are that one should always benchmark instead of making naive assumptions about languages' relative "default" performance. I appreciate the education.
Thanks again to all for your suggestions!
| As a guess, Python strings are reference counted immutable strings, so that no strings are copied around in the Python code, while C++ std::string is a mutable value type, and is copied at the smallest opportunity.
If the goal is fast splitting, then one would use constant time substring operations, which means only referring to parts of the original string, as in Python (and Java, and C#…).
The C++ std::string class has one redeeming feature, though: it is standard, so that it can be used to pass strings safely and portably around where efficiency is not a main consideration. But enough chat. Code -- and on my machine this is of course faster than Python, since Python's string handling is implemented in C which is a subset of C++ (he he):
#include <iostream>
#include <string>
#include <sstream>
#include <time.h>
#include <vector>
using namespace std;
class StringRef
{
private:
char const* begin_;
int size_;
public:
int size() const { return size_; }
char const* begin() const { return begin_; }
char const* end() const { return begin_ + size_; }
StringRef( char const* const begin, int const size )
: begin_( begin )
, size_( size )
{}
};
vector<StringRef> split3( string const& str, char delimiter = ' ' )
{
vector<StringRef> result;
enum State { inSpace, inToken };
State state = inSpace;
char const* pTokenBegin = 0; // Init to satisfy compiler.
for( auto it = str.begin(); it != str.end(); ++it )
{
State const newState = (*it == delimiter? inSpace : inToken);
if( newState != state )
{
switch( newState )
{
case inSpace:
result.push_back( StringRef( pTokenBegin, &*it - pTokenBegin ) );
break;
case inToken:
pTokenBegin = &*it;
}
}
state = newState;
}
if( state == inToken )
{
result.push_back( StringRef( pTokenBegin, &*str.end() - pTokenBegin ) );
}
return result;
}
int main() {
string input_line;
vector<string> spline;
long count = 0;
int sec, lps;
time_t start = time(NULL);
cin.sync_with_stdio(false); //disable synchronous IO
while(cin) {
getline(cin, input_line);
//spline.clear(); //empty the vector for the next line to parse
//I'm trying one of the two implementations, per compilation, obviously:
// split1(spline, input_line);
//split2(spline, input_line);
vector<StringRef> const v = split3( input_line );
count++;
};
count--; //subtract for final over-read
sec = (int) time(NULL) - start;
cerr << "C++ : Saw " << count << " lines in " << sec << " seconds." ;
if (sec > 0) {
lps = count / sec;
cerr << " Crunch speed: " << lps << endl;
} else
cerr << endl;
return 0;
}
//compiled with: g++ -Wall -O3 -o split1 split_1.cpp -std=c++0x
Disclaimer: I hope there aren't any bugs. I haven't tested the functionality, but only checked the speed. But I think, even if there is a bug or two, correcting that won't significantly affect the speed.
| Split | 9,378,500 | 100 |
How can I split a string only once, i.e. make 1|Ceci n'est pas une pipe: | Oui parse to: ["1", "Ceci n'est pas une pipe: | Oui"]?
The limit in split doesn't seem to help...
| You'd want to use String.indexOf('|') to get the index of the first occurrence of '|'.
var i = s.indexOf('|');
var splits = [s.slice(0,i), s.slice(i+1)];
| Split | 2,878,703 | 100 |
I want to split a 400k line long log file from a particular line number.
For this question, lets make this an arbitrary number 300k.
Is there a linux command that allows me to do this (within the script)?
I know split lets me split the file in equal parts either by size or line numbers but that's not what I want. I want to the first 300k in one file and the last 100k in the second file.
Any help would be appreciated. Thanks!
On second thoughts this would be more suited to the superuser or serverfault site.
| file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.
| Split | 3,066,948 | 99 |
I have the following String:
String str = "\nHERE\n\nTHERE\n\nEVERYWHERE\n\n";
If you just print this, it would output like this (Of course the \n wouldn't be "literally" printed):
\n
HERE\n
\n
THERE\n
\n
EVERYWHERE\n
\n
\n
When I call the method split("\n"), I want to get all strings between the new line (\n) characters even empty strings at the end.
For example, if I do this today:
String strArray[] = str.split("\n");
System.out.println("strArray.length - " + strArray.length);
for(int i = 0; i < strArray.length; i++)
System.out.println("strArray[" + i + "] - \"" + strArray[i] + "\"");
I want it to print out like this (Output A):
strArray.length - 8
strArray[0] - ""
strArray[1] - "HERE"
strArray[2] - ""
strArray[3] - "THERE"
strArray[4] - ""
strArray[5] - "EVERYWHERE"
strArray[6] - ""
strArray[7] - ""
Currently, it prints like this (Output B), and any ending empty strings are skipped:
strArray.length - 6
strArray[0] - ""
strArray[1] - "HERE"
strArray[2] - ""
strArray[3] - "THERE"
strArray[4] - ""
strArray[5] - "EVERYWHERE"
How do I make the split() method include the empty strings like in Output A? I, of course, could write a multi-line piece of code, but wanted to know, before I waste my time trying to implement that, if there was a simple method or an extra two or so lines of code to help me. Thanks!
| use str.split("\n", -1) (with a negative limit argument). When split is given zero or no limit argument it discards trailing empty fields, and when it's given a positive limit argument it limits the number of fields to that number, but a negative limit means to allow any number of fields and not discard trailing empty fields. This is documented here and the behavior is taken from Perl.
| Split | 13,939,675 | 97 |
I have a String like this :
String attributes = " foo boo, faa baa, fii bii,"
and I want to get a result like this :
String[] result = {"foo boo", "faa baa", "fii bii"};
So my issue is how should to make split and trim in one shot i already split:
String[] result = attributes.split(",");
But the spaces still in the result :
String[] result = {" foo boo", " faa baa", " fii bii"};
^ ^ ^
I know that we can make a loop and make trim for every one but I want to makes it in shot.
| Use regular expression \s*,\s* for splitting.
String result[] = attributes.split("\\s*,\\s*");
For Initial and Trailing Whitespaces
The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same:
String result[] = attributes.trim().split("\\s*,\\s*");
| Split | 41,953,388 | 94 |
I'm trying to find a Delphi function that will split an input string into an array of strings based on a delimiter. I've found a lot from searching the web, but all seem to have their own issues and I haven't been able to get any of them to work.
I just need to split a string like:
"word:doc,txt,docx" into an array based on ':'. The result would be
['word', 'doc,txt,docx']. How can I do that?
| you can use the TStrings.DelimitedText property for split an string
check this sample
program Project28;
{$APPTYPE CONSOLE}
uses
Classes,
SysUtils;
procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
ListOfStrings.Clear;
ListOfStrings.Delimiter := Delimiter;
ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer.
ListOfStrings.DelimitedText := Str;
end;
var
OutPutList: TStringList;
begin
OutPutList := TStringList.Create;
try
Split(':', 'word:doc,txt,docx', OutPutList) ;
Writeln(OutPutList.Text);
Readln;
finally
OutPutList.Free;
end;
end.
UPDATE
See this link for an explanation of StrictDelimiter.
| Split | 2,625,707 | 94 |
What is the best method of splitting a String into a Stream?
I saw these variations:
Arrays.stream("b,l,a".split(","))
Stream.of("b,l,a".split(","))
Pattern.compile(",").splitAsStream("b,l,a")
My priorities are:
Robustness
Readability
Performance
A complete, compilable example:
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class HelloWorld {
public static void main(String[] args) {
stream1().forEach(System.out::println);
stream2().forEach(System.out::println);
stream3().forEach(System.out::println);
}
private static Stream<String> stream1() {
return Arrays.stream("b,l,a".split(","));
}
private static Stream<String> stream2() {
return Stream.of("b,l,a".split(","));
}
private static Stream<String> stream3() {
return Pattern.compile(",").splitAsStream("b,l,a");
}
}
| Arrays.stream/String.split
Since String.split returns an array String[], I always recommend Arrays.stream as the canonical idiom for streaming over an array.
String input = "dog,cat,bird";
Stream<String> stream = Arrays.stream(input.split( "," ));
stream.forEach(System.out::println);
Stream.of/String.split
Stream.of is a varargs method which just happens to accept an array, due to the fact that varargs methods are implemented via arrays and there were compatibility concerns when varargs were introduced to Java and existing methods retrofitted to accept variable arguments.
Stream<String> stream = Stream.of(input.split(",")); // works, but is non-idiomatic
Stream<String> stream = Stream.of("dog", "cat", "bird"); // intended use case
Pattern.splitAsStream
Pattern.compile(",").splitAsStream(string) has the advantage of streaming directly rather than creating an intermediate array. So for a large number of sub-strings, this can have a performance benefit. On the other hand, if the delimiter is trivial, i.e. a single literal character, the String.split implementation will go through a fast path instead of using the regex engine. So in this case, the answer is not trivial.
Stream<String> stream = Pattern.compile(",").splitAsStream(input);
If the streaming happens inside another stream, e.g. .flatMap(Pattern.compile(pattern) ::splitAsStream) there is the advantage that the pattern has to be analyzed only once, rather than for every string of the outer stream.
Stream<String> stream = Stream.of("a,b", "c,d,e", "f", "g,h,i,j")
.flatMap(Pattern.compile(",")::splitAsStream);
This is a property of method references of the form expression::name, which will evaluate the expression and capture the result when creating the instance of the functional interface, as explained in What is the equivalent lambda expression for System.out::println and java.lang.NullPointerException is thrown using a method-reference but not a lambda expression
| Split | 40,932,813 | 93 |
In JavaScript this is how we can split a string at every 3-rd character
"foobarspam".match(/.{1,3}/g)
I am trying to figure out how to do this in Java. Any pointers?
| You could do it like this:
String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));
which produces:
[123, 456, 789, 0]
The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))
| Split | 2,297,347 | 93 |
I would like to split a String but I would like to keep white space like:
var str = "my car is red";
var stringArray [];
stringArray [0] = "my";
stringArray [1] = " ";
stringArray [2] = "car";
stringArray [3] = " ";
stringArray [4] = "is";
stringArray [5] = " ";
stringArray [6] = "red";
How I can proceed to do that?
Thanks !
| Using regex:
var str = "my car is red";
var stringArray = str.split(/(\s+)/);
console.log(stringArray); // ["my", " ", "car", " ", "is", " ", "red"]
\s matches any character that is a whitespace, adding the plus makes it greedy, matching a group starting with characters and ending with whitespace, and the next group starts when there is a character after the whitespace etc.
| Split | 26,425,637 | 92 |
I have comma separated data in a column:
Column
-------
a,b,c,d
I want to split the comma separated data into multiple columns to get this output:
Column1 Column2 Column3 Column4
------- ------- ------- -------
a b c d
How can this be achieved?
| split_part() does what you want in one step:
SELECT split_part(col, ',', 1) AS col1
, split_part(col, ',', 2) AS col2
, split_part(col, ',', 3) AS col3
, split_part(col, ',', 4) AS col4
FROM tbl;
Add as many lines as you have items in col (the possible maximum).
Columns exceeding data items will be empty strings ('').
| Split | 8,584,967 | 92 |
I'd like to split strings like these
'foofo21'
'bar432'
'foobar12345'
into
['foofo', '21']
['bar', '432']
['foobar', '12345']
Does somebody know an easy and simple way to do this in python?
| I would approach this by using re.match in the following way:
import re
match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I)
if match:
items = match.groups()
print(items)
>> ("foofo", "21")
| Split | 430,079 | 91 |
I have a string that looks like this:
"Name1=Value1;Name2=Value2;Name3=Value3"
Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:
dict = {
"Name1": "Value1",
"Name2": "Value2",
"Name3": "Value3"
}
I have looked through the modules available but can't seem to find anything that matches.
Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.
I'll do it myself then.
| There's no builtin, but you can accomplish this fairly simply with a generator comprehension:
s= "Name1=Value1;Name2=Value2;Name3=Value3"
dict(item.split("=") for item in s.split(";"))
[Edit] From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs):
>>> s = "Name1='Value=2';Name2=Value2;Name3=Value3"
>>> dict(csv.reader([item], delimiter='=', quotechar="'").next()
for item in csv.reader([s], delimiter=';', quotechar="'").next())
{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'}
Depending on the exact structure of your format, you may need to write your own simple parser however.
| Split | 186,857 | 91 |
Let's say I need to split string like this:
Input string: "My. name. is Bond._James Bond!"
Output 2 strings:
"My. name. is Bond"
"_James Bond!"
I tried this:
int lastDotIndex = inputString.LastIndexOf(".", System.StringComparison.Ordinal);
string firstPart = inputString.Remove(lastDotIndex);
string secondPart= inputString.Substring(lastDotIndex + 1, inputString.Length - firstPart.Length - 1);
Can someone propose more elegant way?
| Updated Answer (for C# 8 and above)
C# 8 introduced a new feature called ranges and indices, which offer a more concise syntax for working with strings.
string s = "My. name. is Bond._James Bond!";
int idx = s.LastIndexOf('.');
if (idx != -1)
{
Console.WriteLine(s[..idx]); // "My. name. is Bond"
Console.WriteLine(s[(idx + 1)..]); // "_James Bond!"
}
Original Answer (for C# 7 and below)
This is the original answer that uses the string.Substring(int, int) method. It's still OK to use this method if you prefer.
string s = "My. name. is Bond._James Bond!";
int idx = s.LastIndexOf('.');
if (idx != -1)
{
Console.WriteLine(s.Substring(0, idx)); // "My. name. is Bond"
Console.WriteLine(s.Substring(idx + 1)); // "_James Bond!"
}
| Split | 21,733,756 | 90 |
I have a string "4,6,8\n9,4"
I want to split this based on ,and \n
Output array should be
4
6
8
9
4
Edit :
Now i am reading string from console , when i enter a string as above in console , in the code behind i get as "4,6,8\\n9,4" . Now that i want to split using "," and "\\n" . How can i change the expression ?
| Use string.Split(char [])
string strings = "4,6,8\n9,4";
string [] split = strings .Split(new Char [] {',' , '\n' });
EDIT
Try following if you get any unnecessary empty items. String.Split Method (String[], StringSplitOptions)
string [] split = strings .Split(new Char [] {',' , '\n' },
StringSplitOptions.RemoveEmptyEntries);
EDIT2
This works for your updated question. Add all the necessary split characters to the char [].
string [] split = strings.Split(new Char[] { ',', '\\', '\n' },
StringSplitOptions.RemoveEmptyEntries);
| Split | 7,605,785 | 89 |
Okay, here is my code with details of what I have tried to do:
var str = "Hello m|sss sss|mmm ss";
//Now I separate them by "|"
var str1 = str.split("|");
//Now I want to get the first word of every split-ed sting parts:
for (var i = 0; i < codelines.length; i++) {
//What to do here to get the first word of every spilt
}
So what should I do there? :\
What I want to get is :
firstword[0] will give "Hello"
firstword[1] will give "sss"
firstword[2] will give "mmm"
| Use regular expression
var totalWords = "foo love bar very much.";
var firstWord = totalWords.replace(/ .*/,'');
$('body').append(firstWord);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
| Split | 18,558,417 | 88 |
I want to remove square brackets from a string, but I don't know how.
String str = "[Chrissman-@1]";
str = replaceAll("\\[\\]", "");
String[] temp = str.split("-@");
System.out.println("Nickname: " + temp[0] + " | Power: " + temp[1]);
But my result is: [Chrissman | 1]
The square brackets doesn't get removed.
I tried using a different regex: "\\[.*?\\]", "\\[\\d+\\]"
but the result is the same, the square brackets still attached on the string.
Edit:
I tried:
str.replaceAll("]", "");
str.replaceAll("[", "");
And now I'm getting:
Exception in thread "Thread-4" java.util.regex.PatternSyntaxException: Unclosed character class near index 0
[
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.clazz(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
| The replaceAll method is attempting to match the String literal [] which does not exist within the String try replacing these items separately.
String str = "[Chrissman-@1]";
str = str.replaceAll("\\[", "").replaceAll("\\]","");
| Split | 14,442,162 | 88 |
Suppose I have a table like this:
subject
flag
this is a test
2
subject is of type text, and flag is of type int. I would like to transform this table to something like this in Postgres:
token
flag
this
2
is
2
a
2
test
2
Is there an easy way to do this?
| Use a LATERAL join - with string_to_table() in Postgres 14+.
Minimal form:
SELECT token, flag
FROM tbl, string_to_table(subject, ' ') token
WHERE flag = 2;
The comma in the FROM list is (almost) equivalent to CROSS JOIN, LATERAL is automatically assumed for set-returning functions (SRF) in the FROM list. Why "almost"? See:
"invalid reference to FROM-clause entry for table" in Postgres query
The alias "token" for the derived table is also assumed as column alias for a single anonymous column, and we assumed distinct column names across the query. Equivalent, more verbose and less error-prone:
SELECT s.token, t.flag
FROM tbl t
CROSS JOIN LATERAL string_to_table(subject, ' ') AS s(token)
WHERE t.flag = 2;
Or move the SRF to the SELECT list, which is allowed in Postgres (but not in standard SQL), to (almost) the same effect:
SELECT string_to_table(subject, ' ') AS token, flag
FROM tbl
WHERE flag = 2;
The last one seems acceptable since SRF in the SELECT list have been sanitized in Postgres 10. See:
What is the expected behaviour for multiple set-returning functions in SELECT clause?
If string_to_table() does not return any rows (empty or null subject), the (implicit) join eliminates the row from the result. Use LEFT JOIN ... ON true to keep qualifying rows from tbl. See:
What is the difference between a LATERAL JOIN and a subquery in PostgreSQL?
We could also use regexp_split_to_table(), but that's slower. Regular expressions are powerful but expensive. See:
SQL select rows containing substring in text field
PostgreSQL unnest() with element number
In Postgres 13 or older use unnest(string_to_array(subject, ' ')) instead of string_to_table(subject, ' ').
| Split | 29,419,993 | 86 |
I want to split a string by whitespaces, , and ' using a single ruby command.
word.split will split by white spaces;
word.split(",") will split by ,;
word.split("\'") will split by '.
How to do all three at once?
| word = "Now is the,time for'all good people"
word.split(/[\s,']/)
=> ["Now", "is", "the", "time", "for", "all", "good", "people"]
| Split | 19,509,307 | 86 |
I have this code :
stringCutted = myString.Split("/"). // ???
and I'd like to store in stringCutted the last element of the string[] after the split, directly, quickly, without storing the splitted array in a variable and access to that element with array[array.length].
Is this possible in C#?
| If you're using .NET 3.5 or higher, it's easy using LINQ to Objects:
stringCutted = myString.Split('/').Last();
Note that Last() (without a predicate) is optimized for the case where the source implements IList<T> (as a single-dimensional array does) so this won't iterate over the whole array to find the last element. On the other hand, that optimization is undocumented...
| Split | 7,256,873 | 86 |
String is
ex="test1, test2, test3, test4, test5"
when I use
ex.split(",").first
it returns
"test1"
Now I want to get the remaining items, i.e. `"test2, test3, test4, test5". If I use
ex.split(",").last
it returns only
"test5"
How to get all the remaining items skipping first one?
| Try this:
first, *rest = ex.split(/, /)
Now first will be the first value, rest will be the rest of the array.
| Split | 1,333,347 | 86 |
I'm looking for an equivalent to sscanf() in Python. I want to parse /proc/net/* files, in C I could do something like this:
int matches = sscanf(
buffer,
"%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n",
local_addr, &local_port, rem_addr, &rem_port, &inode);
I thought at first to use str.split, however it doesn't split on the given characters, but the sep string as a whole:
>>> lines = open("/proc/net/dev").readlines()
>>> for l in lines[2:]:
>>> cols = l.split(string.whitespace + ":")
>>> print len(cols)
1
Which should be returning 17, as explained above.
Is there a Python equivalent to sscanf (not RE), or a string splitting function in the standard library that splits on any of a range of characters that I'm not aware of?
| There is also the parse module.
parse() is designed to be the opposite of format() (the newer string formatting function in Python 2.6 and higher).
>>> from parse import parse
>>> parse('{} fish', '1')
>>> parse('{} fish', '1 fish')
<Result ('1',) {}>
>>> parse('{} fish', '2 fish')
<Result ('2',) {}>
>>> parse('{} fish', 'red fish')
<Result ('red',) {}>
>>> parse('{} fish', 'blue fish')
<Result ('blue',) {}>
| Split | 2,175,080 | 84 |
I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.
For instance:
>>> c = "help, me"
>>> print c.split()
['help,', 'me']
What I really want the list to look like is:
['help', ',', 'me']
So, I want the string split at whitespace with the punctuation split from the words.
I've tried to parse the string first and then run the split:
>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
This produces the result I want, but is painfully slow on large files.
Is there a way to do this more efficiently?
| This is more or less the way to do it:
>>> import re
>>> re.findall(r"[\w']+|[.,!?;]", "Hello, I'm a string!")
['Hello', ',', "I'm", 'a', 'string', '!']
The trick is, not to think about where to split the string, but what to include in the tokens.
Caveats:
The underscore (_) is considered an inner-word character. Replace \w, if you don't want that.
This will not work with (single) quotes in the string.
Put any additional punctuation marks you want to use in the right half of the regular expression.
Anything not explicitely mentioned in the re is silently dropped.
| Split | 367,155 | 82 |
How do I split a string by . delimiter in PHP? For example, if I have the string "a.b", how do I get "a"?
| explode does the job:
$parts = explode('.', $string);
You can also directly fetch parts of the result into variables:
list($part1, $part2) = explode('.', $string);
| Split | 5,159,086 | 80 |
I have a string such as:
"0123456789"
And I need to split each character into an array.
I, for the hell of it, tried:
explode('', '123545789');
But it gave me the obvious: Warning: No delimiter defined in explode) ..
How would I come across this? I can't see any method off hand, especially just a function.
| $array = str_split("0123456789bcdfghjkmnpqrstvwxyz");
str_split takes an optional 2nd param, the chunk length (default 1), so you can do things like:
$array = str_split("aabbccdd", 2);
// $array[0] = aa
// $array[1] = bb
// $array[2] = cc etc ...
You can also get at parts of your string by treating it as an array:
$string = "hello";
echo $string[1];
// outputs "e"
| Split | 2,170,320 | 80 |
Suppose I have a string "AAA BBB CCC DDD EEE FFF".
How can I split the string and retrieve the nth substring, in a batch file?
The equivalent in C# would be
"AAA BBB CCC DDD EEE FFF".Split()[n]
| Three possible solutions to iterate through the words of the string:
Version 1:
@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
for %%a in (%s%) do echo %%a
Version 2:
@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
set t=%s%
:loop
for /f "tokens=1*" %%a in ("%t%") do (
echo %%a
set t=%%b
)
if defined t goto :loop
Version 3:
@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
call :sub1 %s%
exit /b
:sub1
if "%1"=="" exit /b
echo %1
shift
goto :sub1
Version 1 does not work when the string contains wildcard characters like '*' or '?'.
Versions 1 and 3 treat characters like '=', ';' or ',' as word separators. These characters have the same effect as the space character.
| Split | 1,707,058 | 80 |
In Perl I can do:
my ($x, $y) = split /:/, $str;
And it will work whether or not the string contains the pattern.
In Python, however this won't work:
a, b = "foo".split(":") # ValueError: not enough values to unpack
What's the canonical way to prevent errors in such cases?
| If you're splitting into just two parts (like in your example) you can use str.partition() to get a guaranteed argument unpacking size of 3:
>>> a, sep, b = 'foo'.partition(':')
>>> a, sep, b
('foo', '', '')
str.partition() always returns a 3-tuple, whether the separator is found or not.
Another alternative for Python 3.x is to use extended iterable unpacking:
>>> a, *b = 'foo'.split(':')
>>> a, b
('foo', [])
This assigns the first split item to a and the list of remaining items (if any) to b.
| Split | 38,149,470 | 79 |
I need to split a number into even parts for example:
32427237 needs to become 324 272 37
103092501 needs to become 103 092 501
How does one go about splitting it and handling odd number situations such as a split resulting in these parts e.g. 123 456 789 0?
| If you have to do that in many places in your code you can create a fancy extension method:
static class StringExtensions {
public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) {
if (s == null)
throw new ArgumentNullException(nameof(s));
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", nameof(partLength));
for (var i = 0; i < s.Length; i += partLength)
yield return s.Substring(i, Math.Min(partLength, s.Length - i));
}
}
You can then use it like this:
var parts = "32427237".SplitInParts(3);
Console.WriteLine(String.Join(" ", parts));
The output is 324 272 37 as desired.
When you split the string into parts new strings are allocated even though these substrings already exist in the original string. Normally, you shouldn't be too concerned about these allocations but using modern C# you can avoid this by altering the extension method slightly to use "spans":
public static IEnumerable<ReadOnlyMemory<char>> SplitInParts(this String s, Int32 partLength)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", nameof(partLength));
for (var i = 0; i < s.Length; i += partLength)
yield return s.AsMemory().Slice(i, Math.Min(partLength, s.Length - i));
}
The return type is changed to public static IEnumerable<ReadOnlyMemory<char>> and the substrings are created by calling Slice on the source which doesn't allocate.
Notice that if you at some point have to convert ReadOnlyMemory<char> to string for use in an API a new string has to be allocated. Fortunately, there exists many .NET Core APIs that uses ReadOnlyMemory<char> in addition to string so the allocation can be avoided.
| Split | 4,133,377 | 77 |
I want to something as simple as turning "this is a test" into
new string[] {"t","h","i","s"," ","i","s"," ","a"," ","t","e","s","t"}
Would I really have to do something like
test = "this is a test".Select(x => x.ToString()).ToArray();
edit: To clarify, I don't want a char array, ideally I want an array of string. I don't really see anything wrong with the above code except for the fact that I would think there is an easier way.
| I believe this is what you're looking for:
char[] characters = "this is a test".ToCharArray();
| Split | 9,846,948 | 76 |
How can I split a string without removing the delimiters?
Let's say I have a string:
var string = "abcdeabcde";
When I do
var newstring = string.split("d"), I get something like this:
["abc","eabc","e"]
But I want to get this:
["abc","d","eabc","d","e"]
When I tried to do my "split2" function, I got all entangled in splice() and indexes and "this" vs "that" and ... aargh! Help! :D
| Try:
"abcdeabcde".split(/(d)/);
| Split | 4,514,144 | 76 |
My program reads a line from a file. This line contains comma-separated text like:
123,test,444,"don't split, this",more test,1
I would like the result of a split to be this:
123
test
444
"don't split, this"
more test
1
If I use the String.split(","), I would get this:
123
test
444
"don't split
this"
more test
1
In other words: The comma in the substring "don't split, this" is not a separator. How to deal with this?
| You can try out this regex:
str.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
This splits the string on , that is followed by an even number of double quotes. In other words, it splits on comma outside the double quotes. This will work provided you have balanced quotes in your string.
Explanation:
, // Split on comma
(?= // Followed by
(?: // Start a non-capture group
[^"]* // 0 or more non-quote characters
" // 1 quote
[^"]* // 0 or more non-quote characters
" // 1 quote
)* // 0 or more repetition of non-capture group (multiple of 2 quotes will be even)
[^"]* // Finally 0 or more non-quotes
$ // Till the end (This is necessary, else every comma will satisfy the condition)
)
You can even type like this in your code, using (?x) modifier with your regex. The modifier ignores any whitespaces in your regex, so it's becomes more easy to read a regex broken into multiple lines like so:
String[] arr = str.split("(?x) " +
", " + // Split on comma
"(?= " + // Followed by
" (?: " + // Start a non-capture group
" [^\"]* " + // 0 or more non-quote characters
" \" " + // 1 quote
" [^\"]* " + // 0 or more non-quote characters
" \" " + // 1 quote
" )* " + // 0 or more repetition of non-capture group (multiple of 2 quotes will be even)
" [^\"]* " + // Finally 0 or more non-quotes
" $ " + // Till the end (This is necessary, else every comma will satisfy the condition)
") " // End look-ahead
);
| Split | 18,893,390 | 75 |
I need to split/divide up a continuous variable into 3 equal sized groups.
Example data frame:
das <- data.frame(anim = 1:15,
wt = c(181,179,180.5,201,201.5,245,246.4,
189.3,301,354,369,205,199,394,231.3))
After being cut up (according to the value of wt), I would need to have the 3 classes under the new variable wt2 like this:
> das
anim wt wt2
1 1 181.0 1
2 2 179.0 1
3 3 180.5 1
4 4 201.0 2
5 5 201.5 2
6 6 245.0 2
7 7 246.4 3
8 8 189.3 1
9 9 301.0 3
10 10 354.0 3
11 11 369.0 3
12 12 205.0 2
13 13 199.0 1
14 14 394.0 3
15 15 231.3 2
This would be applied to a large data set.
| Or see cut_number from the ggplot2 package, e.g.
das$wt_2 <- as.numeric(cut_number(das$wt,3))
Note that cut(...,3) divides the range of the original data into three ranges of equal lengths; it doesn't necessarily result in the same number of observations per group if the data are unevenly distributed (you can replicate what cut_number does by using quantile appropriately, but it's a nice convenience function). On the other hand, Hmisc::cut2() using the g= argument does split by quantiles, so is more or less equivalent to ggplot2::cut_number. I might have thought that something like cut_number would have made its way into dplyr by so far, but as far as I can tell it hasn't.
| Split | 6,104,836 | 74 |
Our application is mining names from people using Twitter to login.
Twitter is providing full names in a single string.
Examples
1. "Froederick Frankenstien"
2. "Ludwig Van Beethoven"
3. "Anne Frank"
I'd like to split the string into only two vars (first and last) based on the first " " (space) found.
Example First Name Last Name
1 Froederick Frankenstein
2 Ludwig Van Beethoven
3 Anne Frank
I'm familiar with String#split but I'm not sure how to only split once. The most Ruby-Way™ (elegant) answer will be accepted.
| String#split takes a second argument, the limit.
str.split(' ', 2)
should do the trick.
| Split | 5,253,439 | 74 |
I am trying to print the last part of a string before a certain character.
I'm not quite sure whether to use the string .split() method or string slicing or maybe something else.
Here is some code that doesn't work but I think shows the logic:
x = 'http://test.com/lalala-134'
print x['-':0] # beginning at the end of the string, return everything before '-'
Note that the number at the end will vary in size so I can't set an exact count from the end of the string.
| You are looking for str.rsplit(), with a limit:
print x.rsplit('-', 1)[0]
.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.
Another option is to use str.rpartition(), which will only ever split just once:
print x.rpartition('-')[0]
For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().
Demo:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
and the same with str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
| Split | 15,851,568 | 73 |
I have an array with a list of objects. I want to split this array at one particular index, say 4 (this in real is a variable). I want to store the second part of the split array into another array. Might be simple, but I am unable to think of a nice way to do this.
| Use slice, as such:
var ar = [1,2,3,4,5,6];
var p1 = ar.slice(0,4);
console.log({p1});
var p2 = ar.slice(4);
console.log({p2});
| Split | 6,872,630 | 72 |
I'm using the boost::split method to split a string as this:
I first make sure to include the correct header to have access to boost::split:
#include <boost/algorithm/string.hpp>
then:
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
and the line is like
"test test2 test3"
This is how I consume the result string vector:
void printstrs(vector<string> strs)
{
for(vector<string>::iterator it = strs.begin();it!=strs.end();++it)
{
cout << *it << "-------";
}
cout << endl;
}
But why in the result strs I only get "test2" and "test3", shouldn't be "test", "test2" and "test3", there are \t (tab) in the string.
Updated Apr 24th, 2011: It seemed after I changed one line of code at printstrs I can see the first string. I changed
cout << *it << "-------";
to
cout << *it << endl;
And it seemed "-------" covered the first string somehow.
| The problem is somewhere else in your code, because this works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (size_t i = 0; i < strs.size(); i++)
cout << strs[i] << endl;
and testing your approach, which uses a vector iterator also works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
cout << *it << endl;
}
Again, your problem is somewhere else. Maybe what you think is a \t character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.
Output:
* size of the vector: 3
test
test2
test3
| Split | 5,734,304 | 72 |
I have a comma separated file with many lines similar to one below.
Sachin,,M,"Maths,Science,English",Need to improve in these subjects.
Quotes is used to escape the delimiter comma used to represent multiple values.
Now how do I split the above value on the comma delimiter using String.split() if at all its possible?
| public static void main(String[] args) {
String s = "Sachin,,M,\"Maths,Science,English\",Need to improve in these subjects.";
String[] splitted = s.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
System.out.println(Arrays.toString(splitted));
}
Output:
[Sachin, , M, "Maths,Science,English", Need to improve in these subjects.]
| Split | 15,738,918 | 71 |
I'm trying to help out a coworker who accidentally created one feature branch from another feature branch, rather than creating the second one from master. Here is essentially what we have now…
Master ---A---B---C
\
Foo E---F---F---H
\
Bar J---K---L---M
And here is what we'd like to have…
Master ---A---B---C
|\
Foo | E---F---F---H
|
Bar J---K---L---M
One way I thought of would be to create FooV2 and BarV2 branches, and cherry-pick the individual commits into the appropriate V2 branches. But I'm curious, is there a better way to handle this situation?
| For a more general answer that will help us understand things a bit better than just "run this command", we need a larger example. So, let's pretend you're actually in this situation:
---A---B---C <= Master
\
E---F---F---H <= Foo
\
J---K---L---M <= Bar
\
N---O---P---Q <= Baz
And here is what we'd like to have…
---A---B---C <= Master
|\
| E---F---F---H <= Foo
|\
| J---K---L---M <= Bar
\
N---O---P---Q <= Baz
Thankfully, Git has a solution for us in the options to the rebase command!
git rebase --onto [newParent] [oldParent] [branchToMove]
What this means can be broken down into parts:
rebase - Change the parents of something
--onto - This is the flag that tells git to use this alternate rebase syntax
newParent - This is the branch that the branch you are rebasing will have as it's parent
oldParent - This is the branch that the branch you are rebasing currently has as it's parent
branchToMove - This is the branch that you are moving (rebasing)
The bit about "old parent branch" can be a little confusing, but what it's really doing is it's saying "ignore the changes from my old parent when doing the rebase". The oldParent is how you define where the branch you are moving (ie. branchToMove) starts.
So, what are the commands to execute in our situation?
git rebase --onto Master Bar Baz
git rebase --onto Master Foo Bar
Note that the order of these commands matter because we need to pull each branch off of the end of the "branch chain".
| Split | 12,355,904 | 71 |
I am making a method so your password needs at least one captial and one symbol or number.
I was thinking of splitting the string in to lose chars and then use preggmatch to count if it contains one capital and symbol/number.
however i did something like this in action script but can't figure out how this is called in php. i cant find a way to put every char of a word in a array.
AS3 example
for(var i:uint = 0; i < thisWordCode.length -1 ; i++)
{
thisWordCodeVerdeeld[i] = thisWordCode.charAt(i);
//trace (thisWordCodeVerdeeld[i]);
}
Thanks,
Matthy
| you can convert a string to array with str_split and use foreach
$chars = str_split($str);
foreach($chars as $char){
// your code
}
| Split | 1,293,950 | 70 |
What's the best way to slice the last word from a block of text?
I can think of
Split it to a list (by spaces) and removing the last item, then reconcatenating the list.
Use a regular expression to replace the last word.
I'm currently taking approach #1, but I don't know how to concatenate the list...
content = content[position-1:position+249] # Content
words = string.split(content, ' ')
words = words[len[words] -1] # Cut of the last word
Any code examples are much appreciated.
| Actually you don't need to split all words. You can split your text by last space symbol into two parts using rsplit.
Example:
>>> text = 'Python: Cut off the last word of a sentence?'
>>> text.rsplit(' ', 1)[0]
'Python: Cut off the last word of a'
rsplit is a shorthand for "reverse split", and unlike regular split works from the end of a string. The second parameter is a maximum number of splits to make - e.g. value of 1 will give you two-element list as a result (since there was a single split made, which resulted in two pieces of the input string).
| Split | 6,266,727 | 69 |
I think in Python 3 I'll be able to do:
first, *rest = l
which is exactly what I want, but I'm using 2.6. For now I'm doing:
first = l[0]
rest = l[1:]
This is fine, but I was just wondering if there's something more elegant.
| first, rest = l[0], l[1:]
Basically the same, except that it's a oneliner. Tuple assigment rocks.
This is a bit longer and less obvious, but generalized for all iterables (instead of being restricted to sliceables):
i = iter(l)
first = next(i) # i.next() in older versions
rest = list(i)
| Split | 3,513,947 | 69 |
I have a string in the following format:
string1:string2:string3:string4:string5
I'm trying to use sed to split the string on : and print each sub-string on a new line. Here is what I'm doing:
cat ~/Desktop/myfile.txt | sed s/:/\\n/
This prints:
string1
string2:string3:string4:string5
How can I get it to split on each delimiter?
| To split a string with a delimiter with GNU sed you say:
sed 's/delimiter/\n/g' # GNU sed
For example, to split using : as a delimiter:
$ sed 's/:/\n/g' <<< "he:llo:you"
he
llo
you
Or with a non-GNU sed:
$ sed $'s/:/\\\n/g' <<< "he:llo:you"
he
llo
you
In this particular case, you missed the g after the substitution. Hence, it is just done once. See:
$ echo "string1:string2:string3:string4:string5" | sed s/:/\\n/g
string1
string2
string3
string4
string5
g stands for global and means that the substitution has to be done globally, that is, for any occurrence. See that the default is 1 and if you put for example 2, it is done 2 times, etc.
All together, in your case you would need to use:
sed 's/:/\\n/g' ~/Desktop/myfile.txt
Note that you can directly use the sed ... file syntax, instead of unnecessary piping: cat file | sed.
| Split | 18,234,378 | 68 |
To make things simple:
string streamR = sr.ReadLine(); // sr.Readline results in:
// one "two two"
I want to be able to save them as two different strings, remove all spaces EXCEPT for the spaces found between quotation marks. Therefore, what I need is:
string 1 = one
string 2 = two two
So far what I have found that works is the following code, but it removes the spaces within the quotes.
//streamR.ReadLine only has two strings
string[] splitter = streamR.Split(' ');
str1 = splitter[0];
// Only set str2 if the length is >1
str2 = splitter.Length > 1 ? splitter[1] : string.Empty;
The output of this becomes
one
two
I have looked into Regular Expression to split on spaces unless in quotes however I can't seem to get regex to work/understand the code, especially how to split them so they are two different strings. All the codes there give me a compiling error (I am using System.Text.RegularExpressions)
| string input = "one \"two two\" three \"four four\" five six";
var parts = Regex.Matches(input, @"[\""].+?[\""]|[^ ]+")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
| Split | 14,655,023 | 67 |
First I set a variable, and set it to empty:
var str = "";
Then I split it through "&":
var strs = str.split('&');
In the end, I show strs's length:
alert( strs.length);
It alert "1".
But I assign nothing to the 'str' variable. Why does it still have a length, should't it be zero?
| From the MDC doc center:
Note: When the string is empty, split returns an array containing one empty string, rather than an empty array.
Read the full docs here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
In other words, this is by design, and not an error :)
| Split | 5,164,883 | 66 |
Given a character string
test_1<-"abc def,ghi klm"
test_2<-"abc, def ghi klm"
I wish to obtain
"abc"
"def"
"ghi"
However, using strsplit, one must know the order of the splitting values in the string, as strsplit uses the first value to do the first split, the second to do the second... and then recycles.
But this does not:
strsplit(test_1, c(",", " "))
strsplit(test_2, c(" ", ","))
strsplit(test_2, split=c("[:punct:]","[:space:]"))[[1]]
I am looking to split the string wherever I find any of my splitting values in a single step.
| Actually strsplit uses grep patterns as well. (A comma is a regex metacharacter whereas a space is not; hence the need for double escaping the commas in the pattern argument. So the use of "\\s" would be more to improve readability than of necessity):
> strsplit(test_1, "\\, |\\,| ") # three possibilities OR'ed
[[1]]
[1] "abc" "def" "ghi" "klm"
> strsplit(test_2, "\\, |\\,| ")
[[1]]
[1] "abc" "def" "ghi" "klm"
Without using both \\, and \\, (note extra space that SO does not show) you would have gotten some character(0) values. Might have been clearer if I had written:
> strsplit(test_2, "\\,\\s|\\,|\\s")
[[1]]
[1] "abc" "def" "ghi" "klm"
@Fojtasek is so right: Using character classes often simplifies the task because it creates an implicit logical OR:
> strsplit(test_2, "[, ]+")
[[1]]
[1] "abc" "def" "ghi" "klm"
> strsplit(test_1, "[, ]+")
[[1]]
[1] "abc" "def" "ghi" "klm"
| Split | 10,738,729 | 66 |
Subsets and Splits